PostgreSQL是什么?世界上最先进的开源关系数据库
Database

PostgreSQL是什么?世界上最先进的开源关系数据库

PostgreSQL是领先的开源关系数据库管理系统,支持ACID、MVCC、JSON/JSONB和数百个扩展。学习如何用Python和Node.js连接和查询PostgreSQL。

系列文章: 数据库
  1. 1 PostgreSQL是什么?世界上最先进的开源关系数据库
  2. 2 MongoDB是什么?文档数据库与何时选择NoSQL
✦ 快速摘要
PostgreSQL是领先的开源关系数据库管理系统,支持ACID、MVCC、JSON/JSONB和数百个扩展。学习如何用Python和Node.js连接和查询PostgreSQL。
这篇文章怎么样?

PostgreSQL是被誉为"世界上最先进的开源数据库"的关系数据库管理系统——Instagram、Shopify、Discord和全球数千家初创公司的首选。本文介绍PostgreSQL是什么、其架构如何运作,以及如何用Python和Node.js实际连接使用。

PostgreSQL是什么?

PostgreSQL(发音为"post-gres-Q-L"或简称"postgres")是一款开源关系数据库管理系统(RDBMS),起源于1986年加州大学伯克利分校Michael Stonebraker教授主导的POSTGRES项目。1996年该项目更名为PostgreSQL,发展成为独立的开源社区。

PostgreSQL的突出之处在于一种罕见的结合:严格遵循SQL标准的同时,支持JSON/JSONB、数组、自定义数据类型,以及超过100个强大的扩展,例如PostGIS(地理空间数据)和pgvector(AI向量嵌入)。

PostgreSQL架构

当应用程序连接到PostgreSQL时,处理流程如下:

  1. 客户端Postmaster(主管理进程)发送连接请求
  2. Postmaster为每个连接派生专属的后端进程
  3. 后端通过共享缓冲区(共享内存缓存)进行读写
  4. 数据持久化到磁盘上的数据文件

PostgreSQL使用每连接一个进程的模型(每个客户端对应一个OS进程),与MySQL使用线程的方式不同。这也是为什么在扩展到数千个并发连接时,PgBouncer等连接池工具变得至关重要。

ACID与MVCC

PostgreSQL通过MVCC(多版本并发控制)机制保证完整的ACID合规性:更新一行时,Postgres不是覆盖而是创建新版本——读取者看到旧版本,写入者创建新版本。结果:读不阻塞写,写不阻塞读

用Python和Node.js连接PostgreSQL

Python使用psycopg2:

Python
 1import psycopg2
 2
 3conn = psycopg2.connect(
 4    host="localhost",
 5    port=5432,
 6    dbname="mydb",
 7    user="postgres",
 8    password="secret"
 9)
10cur = conn.cursor()
11
12# 使用参数化查询插入数据(防止SQL注入)
13cur.execute(
14    "INSERT INTO users (name, email) VALUES (%s, %s)",
15    ("Alice", "alice@example.com")
16)
17conn.commit()
18
19# 查询
20cur.execute("SELECT id, name FROM users WHERE active = %s", (True,))
21rows = cur.fetchall()
22for row in rows:
23    print(row)  # (1, 'Alice')
24
25cur.close()
26conn.close()

Node.js使用pg:

JavaScript
 1const { Pool } = require('pg');
 2
 3const pool = new Pool({
 4  host: 'localhost',
 5  port: 5432,
 6  database: 'mydb',
 7  user: 'postgres',
 8  password: 'secret',
 9});
10
11async function getActiveUsers() {
12  const result = await pool.query(
13    'SELECT id, name FROM users WHERE active = $1',
14    [true]
15  );
16  return result.rows; // [{ id: 1, name: 'Alice' }]
17}

psql命令行基础命令:

Bash
1psql -h localhost -U postgres -d mydb
2
3# 在psql中
4\dt              -- 列出所有表
5\d users         -- 查看users表结构
6\timing on       -- 开启查询计时

PostgreSQL中的索引

PostgreSQL支持多种索引类型,最常用的:

类型 使用场景 示例
B-tree 默认,用于=<>BETWEEN CREATE INDEX ON users(email)
GIN 搜索JSONB、数组、全文索引 CREATE INDEX ON posts USING GIN(tags)
部分索引 只对行的子集建立索引 CREATE INDEX ON orders(created_at) WHERE status = 'pending'
SQL
1-- email上的B-tree索引
2CREATE INDEX idx_users_email ON users(email);
3
4-- 用于查询JSONB的GIN索引
5CREATE INDEX idx_products_meta ON products USING GIN(metadata);
6
7-- 未处理订单的部分索引
8CREATE INDEX idx_pending_orders ON orders(created_at)
9WHERE status = 'pending';

PostgreSQL vs MySQL — 何时选择哪个?

标准 PostgreSQL MySQL
JSON支持 带索引的JSONB 基本JSON
全文搜索 内置 有限
数据类型 丰富(数组、hstore、范围类型) 基本
复制 逻辑复制+流复制 Binary log
许可证 PostgreSQL(免费,商业可用) GPL

选择PostgreSQL:需要复杂查询、严格ACID合规或JSON混合方案时。选择MySQL:使用WordPress/LAMP技术栈或需要更广泛的PHP生态系统时。

实际应用案例

  • Instagram:使用PostgreSQL管理整个社交图谱和媒体元数据
  • Shopify:PostgreSQL作为数百万商家的主数据存储
  • Stripe:PostgreSQL作为处理数十亿美元交易的支付系统的主数据库

Redis是什么?内存数据库的缓存、发布订阅和队列

MongoDB是什么?文档数据库与何时选择NoSQL

API是什么?REST API及其工作原理

常见问题Q&A
PostgreSQL和MySQL最重要的区别是什么?
PostgreSQL对MVCC(多版本并发控制)的实现更为纯粹,拥有更丰富的数据类型(JSONB、数组、hstore、自定义类型),并且更严格地遵循SQL标准。MySQL/MariaDB在简单的读密集型工作负载中更快,但当需要高数据一致性和复杂查询时,PostgreSQL是首选。
PostgreSQL中的ACID是什么意思?
ACID是保证事务可靠性的四个属性:原子性(Atomicity,整个事务要么成功要么完全回滚)、一致性(Consistency,数据始终处于有效状态)、隔离性(Isolation,并发事务之间互不干扰)、持久性(Durability,已提交的数据即使系统崩溃也永久保存)。
MVCC是什么,为什么重要?
MVCC(多版本并发控制)允许多个事务同时读写而不互相阻塞。当你更新一行时,PostgreSQL创建新版本而不是覆盖——读取者看到旧版本,写入者创建新版本。结果:读取永远不会阻塞写入,写入也不会阻塞读取。
PostgreSQL可以存储JSON数据吗?
可以。PostgreSQL支持两种类型:JSON(存储原始JSON文本)和JSONB(存储已解析的二进制格式,支持索引和更快的查询)。JSONB适合大多数场景,因为它支持@>、?运算符以及创建GIN索引在文档内部搜索。
什么时候应该用PostgreSQL而不是MongoDB?
当数据具有清晰的结构和表间关系(JOIN)、需要完整的ACID合规性用于金融或电商事务、或需要使用GROUP BY和窗口函数进行复杂查询时,选择PostgreSQL。当schema频繁变更、数据天然是嵌套文档格式、或需要快速水平扩展时,选择MongoDB。
PostgreSQL可以免费使用吗?
可以。PostgreSQL采用PostgreSQL许可证发布——一种类BSD/MIT的许可证,允许在商业产品中免费使用、修改和分发。没有付费企业版——所有功能都包含在开源版本中。

PostgreSQL is the open-source relational database management system dubbed "the world's most advanced open source database" — the top choice for Instagram, Shopify, Discord, and thousands of startups worldwide. This article explains what PostgreSQL is, how its architecture works, and how to connect to it in practice using Python and Node.js.

What is PostgreSQL?

PostgreSQL (pronounced "post-gres-Q-L" or simply "postgres") is an open-source relational database management system (RDBMS) that originated from the POSTGRES project at UC Berkeley in 1986, led by Professor Michael Stonebraker. In 1996 the project was renamed PostgreSQL and evolved into an independent open-source community.

What makes PostgreSQL stand out is a rare combination: strict adherence to the SQL standard while also supporting JSON/JSONB, arrays, custom data types, and over 100 powerful extensions such as PostGIS (geospatial data) and pgvector (vector embeddings for AI).

PostgreSQL Architecture

When an application connects to PostgreSQL, the processing flow is as follows:

  1. The Client sends a connection to the Postmaster (the main managing process)
  2. The Postmaster forks a dedicated Backend process for each connection
  3. The Backend reads and writes through the Shared Buffer (shared memory cache)
  4. Data is persisted to Data Files on disk

PostgreSQL uses a process-per-connection model (one OS process per client), unlike MySQL which uses threads. This is why a connection pooler such as PgBouncer becomes important when scaling to thousands of concurrent connections.

ACID and MVCC

PostgreSQL guarantees full ACID compliance through MVCC (Multi-Version Concurrency Control): when a row is updated, Postgres does not overwrite it but instead creates a new version — readers see the old version while the writer creates the new one. The result: reads never block writes, and writes never block reads.

Connecting to PostgreSQL with Python and Node.js

Python with psycopg2:

Python
 1import psycopg2
 2
 3conn = psycopg2.connect(
 4    host="localhost",
 5    port=5432,
 6    dbname="mydb",
 7    user="postgres",
 8    password="secret"
 9)
10cur = conn.cursor()
11
12# Insert with parameterized query (prevents SQL injection)
13cur.execute(
14    "INSERT INTO users (name, email) VALUES (%s, %s)",
15    ("Alice", "alice@example.com")
16)
17conn.commit()
18
19# Select
20cur.execute("SELECT id, name FROM users WHERE active = %s", (True,))
21rows = cur.fetchall()
22for row in rows:
23    print(row)  # (1, 'Alice')
24
25cur.close()
26conn.close()

Node.js with pg:

JavaScript
 1const { Pool } = require('pg');
 2
 3const pool = new Pool({
 4  host: 'localhost',
 5  port: 5432,
 6  database: 'mydb',
 7  user: 'postgres',
 8  password: 'secret',
 9});
10
11async function getActiveUsers() {
12  const result = await pool.query(
13    'SELECT id, name FROM users WHERE active = $1',
14    [true]
15  );
16  return result.rows; // [{ id: 1, name: 'Alice' }]
17}

Basic psql CLI commands:

Bash
1psql -h localhost -U postgres -d mydb
2
3# Inside psql
4\dt              -- list all tables
5\d users         -- show users table structure
6\timing on       -- enable query timing

Indexing in PostgreSQL

PostgreSQL supports multiple index types. The most common:

Type Use when Example
B-tree Default; for =, <, >, BETWEEN CREATE INDEX ON users(email)
GIN Searching inside JSONB, arrays, full-text CREATE INDEX ON posts USING GIN(tags)
Partial Index only a subset of rows CREATE INDEX ON orders(created_at) WHERE status = 'pending'
SQL
1-- B-tree index on email
2CREATE INDEX idx_users_email ON users(email);
3
4-- GIN index for querying JSONB
5CREATE INDEX idx_products_meta ON products USING GIN(metadata);
6
7-- Partial index for unprocessed orders
8CREATE INDEX idx_pending_orders ON orders(created_at)
9WHERE status = 'pending';

PostgreSQL vs MySQL — When to Choose Which?

Criterion PostgreSQL MySQL
JSON support JSONB with indexes Basic JSON
Full-text search Built-in Limited
Data types Rich (arrays, hstore, ranges) Basic
Replication Logical + streaming Binary log
License PostgreSQL (free, commercial ok) GPL

Choose PostgreSQL when you need complex queries, strict ACID compliance, or a JSON hybrid approach. Choose MySQL when working with a WordPress/LAMP stack or when you need the broader PHP ecosystem.

Real-world Use Cases

  • Instagram: uses PostgreSQL for the entire social graph and media metadata
  • Shopify: PostgreSQL as the primary store for millions of merchants
  • Stripe: PostgreSQL as the primary database for a payment system processing billions of dollars

What is Redis? Cache, Pub/Sub and queues with in-memory database

What is MongoDB? Document database and when to choose NoSQL

What is an API? REST API and how it works

Frequently Asked QuestionsQ&A
What is the most important difference between PostgreSQL and MySQL?
PostgreSQL implements MVCC (Multi-Version Concurrency Control) more purely, offers richer data types (JSONB, arrays, hstore, custom types), and adheres more strictly to the SQL standard. MySQL/MariaDB is faster for simple read-heavy workloads, but PostgreSQL is the choice when you need high data consistency and complex queries.
What does ACID mean in PostgreSQL?
ACID is four properties that guarantee reliable transactions: Atomicity (the entire transaction either succeeds or rolls back completely), Consistency (data always remains in a valid state), Isolation (concurrent transactions do not interfere with each other), and Durability (committed data is permanently stored even if the system crashes).
What is MVCC and why does it matter?
MVCC (Multi-Version Concurrency Control) allows multiple transactions to read and write simultaneously without blocking each other. When you update a row, PostgreSQL creates a new version instead of overwriting — readers see the old version while the writer creates the new one. The result: reads never block writes, and writes never block reads.
Can PostgreSQL store JSON data?
Yes. PostgreSQL supports two types: JSON (stores raw JSON text) and JSONB (stores a parsed binary representation, supporting indexes and faster queries). JSONB is recommended for most use cases because it allows the @>, ? operators and GIN indexes for searching inside documents.
When should I use PostgreSQL instead of MongoDB?
Choose PostgreSQL when your data has a clear structure with relationships between tables (JOINs), you need full ACID compliance for financial or e-commerce transactions, or you need complex queries with GROUP BY and window functions. Choose MongoDB when the schema changes frequently, data is naturally nested documents, or you need rapid horizontal scaling.
Is PostgreSQL free to use?
Yes. PostgreSQL is released under the PostgreSQL License — a permissive BSD/MIT-style license that allows free use, modification, and distribution even in commercial products. There is no paid Enterprise edition — all features are available in the open-source release.