PostgreSQL 模式
PostgreSQL 最佳实践的快速参考。如需详细指南,请使用 database-reviewer agent。
何时启用
- 编写 SQL 查询或 migration 时
- 设计数据库 schema 时
- 排查慢查询时
- 实施 Row Level Security 时
- 配置 connection pooling 时
快速参考
索引速查表
| 查询模式 | 索引类型 | 示例 |
|---|
WHERE col = value | B-tree(默认) | CREATE INDEX idx ON t (col) |
WHERE col > value | B-tree | CREATE INDEX idx ON t (col) |
WHERE a = x AND b > y | Composite | CREATE INDEX idx ON t (a, b) |
WHERE jsonb @> '{}' | GIN | CREATE INDEX idx ON t USING gin (col) |
WHERE tsv @@ query | GIN | CREATE INDEX idx ON t USING gin (col) |
| 时间序列范围 | BRIN | CREATE INDEX idx ON t USING brin (col) |
数据类型快速参考
| 使用场景 | 正确类型 | 避免 |
|---|
| ID | bigint | int、随机 UUID |
| 字符串 | text | varchar(255) |
| 时间戳 | timestamptz | timestamp |
| 金额 | numeric(10,2) | float |
| 标志 | boolean | varchar、int |
常见模式
Composite 索引顺序:
-- 先等值列,后范围列
CREATE INDEX idx ON orders (status, created_at);
-- 适用于:WHERE status = 'pending' AND created_at > '2024-01-01'
Covering 索引:
CREATE INDEX idx ON users (email) INCLUDE (name, created_at);
-- 为 SELECT …