PostgreSQL Best Practices
Comprehensive PostgreSQL reference consolidating performance optimization (Supabase), common patterns, and schema design guidance. Covers 8 rule categories prioritized by impact, plus detailed data type and table design reference.
When to Use
Reference these guidelines when:
- Writing SQL queries, migrations, or designing schemas
- Implementing indexes or query optimization
- Reviewing database performance issues
- Configuring connection pooling or scaling
- Optimizing for Postgres-specific features
- Working with Row-Level Security (RLS)
- Choosing data types, constraints, or table structures
- Troubleshooting slow queries
Rule Categories by Priority
| Priority |
Category |
Impact |
Prefix |
| 1 |
Query Performance |
CRITICAL |
query- |
| 2 |
Connection Management |
CRITICAL |
conn- |
| 3 |
Security & RLS |
CRITICAL |
security- |
| 4 |
Schema Design |
HIGH |
schema- |
| 5 |
Concurrency & Locking |
MEDIUM-HIGH |
lock- |
| 6 |
Data Access Patterns |
MEDIUM |
data- |
| 7 |
Monitoring & Diagnostics |
LOW-MEDIUM |
monitor- |
| 8 |
Advanced Features |
LOW |
advanced- |
Detailed Rule Files
Read individual rule files for detailed explanations and SQL examples:
rules/query-missing-indexes.md
rules/schema-partial-indexes.md
rules/_sections.md
Each rule file contains:
- Brief explanation of why it matters
- Incorrect SQL example with explanation
- Correct SQL example with explanation
- Optional EXPLAIN output or metrics
- Additional context and references
- Supabase-specific notes (when applicable)
For the complete compiled guide with all rules expanded: AGENTS.md
Schema Design: Core Rules
- Define a PRIMARY KEY for reference tables (users, orders, etc.). Not always needed for time-series/event/log data. When used, prefer
BIGINT GENERATED ALWAYS AS IDENTITY; use UUID only when global uniqueness/opacity is needed.
- Normalize first (to 3NF) to eliminate data redundancy and update anomalies; denormalize only for measured, high-ROI reads where join performance is proven problematic. Premature denormalization creates maintenance burden.
- Add NOT NULL everywhere it's semantically required; use DEFAULTs for common values.
- Create indexes for access paths you actually query: PK/unique (auto), FK columns (manual!), frequent filters/sorts, and join keys.
- Prefer TIMESTAMPTZ for event time; NUMERIC for money; TEXT for strings; BIGINT for integer values, DOUBLE PRECISION for floats (or
NUMERIC for exact decimal arithmetic).
PostgreSQL "Gotchas"
- Identifiers: unquoted → lowercased. Avoid quoted/mixed-case names. Convention: use
snake_case for table/column names.
- Unique + NULLs: UNIQUE allows multiple NULLs. Use
UNIQUE (...) NULLS NOT DISTINCT (PG15+) to restrict to one NULL.
- FK indexes: PostgreSQL does not auto-index FK columns. Add them.
- No silent coercions: length/precision overflows error out (no truncation). Example: inserting 999 into
NUMERIC(2,0) fails with error, unlike some databases that silently truncate or round.
- Sequences/identity have gaps (normal; don't "fix"). Rollbacks, crashes, and concurrent transactions create gaps in ID sequences (1, 2, 5, 6...). This is expected behavior—don't try to make IDs consecutive.
- Heap storage: no clustered PK by default (unlike SQL Server/MySQL InnoDB);
CLUSTER is one-off reorganization, not maintained on subsequent inserts. Row order on disk is insertion order unless explicitly clustered.
- MVCC: updates/deletes leave dead tuples; vacuum handles them—design to avoid hot wide-row churn.
Data Types
- IDs:
BIGINT GENERATED ALWAYS AS IDENTITY preferred (GENERATED BY DEFAULT also fine); UUID when merging/federating/used in a distributed system or for opaque IDs. Generate with uuidv7() (preferred if using PG18+) or gen_random_uuid() (if using an older PG version).
- Integers: prefer
BIGINT unless storage space is critical; INTEGER for smaller ranges; avoid SMALLINT unless constrained.
- Floats: prefer
DOUBLE PRECISION over REAL unless storage space is critical. Use NUMERIC for exact decimal arithmetic.
- Strings: prefer
TEXT; if length limits needed, use CHECK (LENGTH(col) <= n) instead of VARCHAR(n); avoid CHAR(n). Use BYTEA for binary data. Large strings/binary (>2KB default threshold) automatically stored in TOAST with compression. TOAST storage: PLAIN (no TOAST), EXTENDED (compress + out-of-line), EXTERNAL (out-of-line, no compress), MAIN (compress, keep in-line if possible). Default EXTENDED usually optimal. Control with ALTER TABLE tbl ALTER COLUMN col SET STORAGE strategy and ALTER TABLE tbl SET (toast_tuple_target = 4096) for threshold. Case-insensitive: for locale/accent handling use non-deterministic collations; for plain ASCII use expression indexes on LOWER(col) (preferred unless column needs case-insensitive PK/FK/UNIQUE) or CITEXT.
- Money:
NUMERIC(p,s) (never float).
- Time:
TIMESTAMPTZ for timestamps; DATE for date-only; INTERVAL for durations. Avoid TIMESTAMP (without timezone). Use now() for transaction start time, clock_timestamp() for current wall-clock time.
- Booleans:
BOOLEAN with NOT NULL constraint unless tri-state values are required.
- Enums:
CREATE TYPE ... AS ENUM for small, stable sets (e.g. US states, days of week). For business-logic-driven and evolving values (e.g. order statuses) → use TEXT (or INT) + CHECK or lookup table.
- Arrays:
TEXT[], INTEGER[], etc. Use for ordered lists where you query elements. Index with GIN for containment (@>, <@) and overlap (&&) queries. Access: arr[1] (1-indexed), arr[1:3] (slicing). Good for tags, categories; avoid for relations—use junction tables instead. Literal syntax: '{val1,val2}' or ARRAY[val1,val2].
- Range types:
daterange, numrange, tstzrange for intervals. Support overlap (&&), containment (@>), operators. Index with GiST. Good for scheduling, versioning, numeric ranges. Pick a bounds scheme and use it consistently; prefer [) (inclusive/exclusive) by default.
- Network types:
INET for IP addresses, CIDR for network ranges, MACADDR for MAC addresses. Support network operators (<<, >>, &&).
- Geometric types:
POINT, LINE, POLYGON, CIRCLE for 2D spatial data. Index with GiST. Consider PostGIS for advanced spatial features.
- Text search:
TSVECTOR for full-text search documents, TSQUERY for search queries. Index tsvector with GIN. Always specify language: to_tsvector('english', col) and to_tsquery('english', 'query'). Never use single-argument versions. This applies to both index expressions and queries.
- Domain types:
CREATE DOMAIN email AS TEXT CHECK (VALUE ~ '^[^@]+@[^@]+$') for reusable custom types with validation. Enforces constraints across tables.
- Composite types:
CREATE TYPE address AS (street TEXT, city TEXT, zip TEXT) for structured data within columns. Access with (col).field syntax.
- JSONB: preferred over JSON; index with GIN. Use only for optional/semi-structured attrs. ONLY use JSON if the original ordering of the contents MUST be preserved.
- Vector types:
vector type by pgvector for vector similarity search for embeddings.
Do Not Use These Data Types
- DO NOT use
timestamp (without time zone); DO use timestamptz instead.
- DO NOT use
char(n) or varchar(n); DO use text instead.
- DO NOT use
money type; DO use numeric instead.
- DO NOT use
timetz type; DO use timestamptz instead.
- DO NOT use
timestamptz(0) or any other precision specification; DO use timestamptz instead.
- DO NOT use
serial type; DO use generated always as identity instead.
Data Type Quick Reference
| Use Case |
Correct Type |
Avoid |
| IDs |
bigint |
int, random UUID |
| Strings |
text |
varchar(255) |
| Timestamps |
timestamptz |
timestamp |
| Money |
numeric(10,2) |
float |
| Flags |
boolean |
varchar, int |
Table Types
- Regular: default; fully durable, logged.
- TEMPORARY: session-scoped, auto-dropped, not logged. Faster for scratch work.
- UNLOGGED: persistent but not crash-safe. Faster writes; good for caches/staging.
Constraints
- PK: implicit UNIQUE + NOT NULL; creates a B-tree index.
- FK: specify
ON DELETE/UPDATE action (CASCADE, RESTRICT, SET NULL, SET DEFAULT). Add explicit index on referencing column—speeds up joins and prevents locking issues on parent deletes/updates. Use DEFERRABLE INITIALLY DEFERRED for circular FK dependencies checked at transaction end.
- UNIQUE: creates a B-tree index; allows multiple NULLs unless
NULLS NOT DISTINCT (PG15+). Standard behavior: (1, NULL) and (1, NULL) are allowed. With NULLS NOT DISTINCT: only one (1, NULL) allowed. Prefer NULLS NOT DISTINCT unless you specifically need duplicate NULLs.
- CHECK: row-local constraints; NULL values pass the check (three-valued logic). Example:
CHECK (price > 0) allows NULL prices. Combine with NOT NULL to enforce: price NUMERIC NOT NULL CHECK (price > 0).
- EXCLUDE: prevents overlapping values using operators.
EXCLUDE USING gist (room_id WITH =, booking_period WITH &&) prevents double-booking rooms. Requires appropriate index type (often GiST).
Indexing
Index Type Reference
| Query Pattern |
Index Type |
Example |
WHERE col = value |
B-tree (default) |
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) |
| Time-series ranges |
BRIN |
CREATE INDEX idx ON t USING brin (col) |
Index Types Explained
- B-tree: default for equality/range queries (
=, <, >, BETWEEN, ORDER BY)
- Composite: order matters—index used if equality on leftmost prefix (
WHERE a = ? AND b > ? uses index on (a,b), but WHERE b = ? does not). Put most selective/frequently filtered columns first.
- Covering:
CREATE INDEX ON tbl (id) INCLUDE (name, email) - includes non-key columns for index-only scans without visiting table.
- Partial: for hot subsets (
WHERE status = 'active' → CREATE INDEX ON tbl (user_id) WHERE status = 'active'). Any query with status = 'active' can use this index.
- Expression: for computed search keys (
CREATE INDEX ON tbl (LOWER(email))). Expression must match exactly in WHERE clause: WHERE LOWER(email) = 'user@example.com'.
- GIN: JSONB containment/existence, arrays (
@>, ?), full-text search (@@)
- GiST: ranges, geometry, exclusion constraints
- BRIN: very large, naturally ordered data (time-series)—minimal storage overhead. Effective when row order on disk correlates with indexed column (insertion order or after
CLUSTER).
Common Index Patterns
Composite Index Order:
-- Equality columns first, then range columns
CREATE INDEX idx ON orders (status, created_at);
-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'
Covering Index:
CREATE INDEX idx ON users (email) INCLUDE (name, created_at);
-- Avoids table lookup for SELECT email, name, created_at
Partial Index:
CREATE INDEX idx ON users (email) WHERE deleted_at IS NULL;
-- Smaller index, only includes active users
Row-Level Security
Enable with ALTER TABLE tbl ENABLE ROW LEVEL SECURITY. Create policies: CREATE POLICY user_access ON orders FOR SELECT TO app_users USING (user_id = current_user_id()). Built-in user-based access control at the row level.
Optimized RLS Policy:
CREATE POLICY policy ON orders
USING ((SELECT auth.uid()) = user_id); -- Wrap in SELECT!
Partitioning
- Use for very large tables (>100M rows) where queries consistently filter on partition key (often time/date).
- Alternate use: use for tables where data maintenance tasks dictates e.g. data pruned or bulk replaced periodically
- RANGE: common for time-series (
PARTITION BY RANGE (created_at)). Create partitions: CREATE TABLE logs_2024_01 PARTITION OF logs FOR VALUES FROM ('2024-01-01') TO ('2024-02-01'). TimescaleDB automates time-based or ID-based partitioning with retention policies and compression.
- LIST: for discrete values (
PARTITION BY LIST (region)). Example: FOR VALUES IN ('us-east', 'us-west').
- HASH: for even distribution when no natural key (
PARTITION BY HASH (user_id)). Creates N partitions with modulus.
- Constraint exclusion: requires
CHECK constraints on partitions for query planner to prune. Auto-created for declarative partitioning (PG10+).
- Prefer declarative partitioning or hypertables. Do NOT use table inheritance.
- Limitations: no global UNIQUE constraints—include partition key in PK/UNIQUE. FKs from partitioned tables not supported; use triggers.
Special Considerations
Update-Heavy Tables
- Separate hot/cold columns—put frequently updated columns in separate table to minimize bloat.
- Use
fillfactor=90 to leave space for HOT updates that avoid index maintenance.
- Avoid updating indexed columns—prevents beneficial HOT updates.
- Partition by update patterns—separate frequently updated rows in a different partition from stable data.
Insert-Heavy Workloads
- Minimize indexes—only create what you query; every index slows inserts.
- Use
COPY or multi-row INSERT instead of single-row inserts.
- UNLOGGED tables for rebuildable staging data—much faster writes.
- Defer index creation for bulk loads—>drop index, load data, recreate indexes.
- Partition by time/hash to distribute load. TimescaleDB automates partitioning and compression of insert-heavy data.
- Use a natural key for primary key such as a (timestamp, device_id) if enforcing global uniqueness is important many insert-heavy tables don't need a primary key at all.
- If you do need a surrogate key, Prefer
BIGINT GENERATED ALWAYS AS IDENTITY over UUID.
Upsert-Friendly Design
- Requires UNIQUE index on conflict target columns—
ON CONFLICT (col1, col2) needs exact matching unique index (partial indexes don't work).
- Use
EXCLUDED.column to reference would-be-inserted values; only update columns that actually changed to reduce write overhead.
DO NOTHING faster than DO UPDATE when no actual update needed.
Safe Schema Evolution
- Transactional DDL: most DDL operations can run in transactions and be rolled back—
BEGIN; ALTER TABLE...; ROLLBACK; for safe testing.
- Concurrent index creation:
CREATE INDEX CONCURRENTLY avoids blocking writes but can't run in transactions.
- Volatile defaults cause rewrites: adding
NOT NULL columns with volatile defaults (e.g., now(), gen_random_uuid()) rewrites entire table. Non-volatile defaults are fast.
- Drop constraints before columns:
ALTER TABLE DROP CONSTRAINT then DROP COLUMN to avoid dependency issues.
- Function signature changes:
CREATE OR REPLACE with different arguments creates overloads, not replacements. DROP old version if no overload desired.
Generated Columns
... GENERATED ALWAYS AS (<expr>) STORED for computed, indexable fields. PG18+ adds VIRTUAL columns (computed on read, not stored).
JSONB Guidance
- Prefer
JSONB with GIN index.
- Default:
CREATE INDEX ON tbl USING GIN (jsonb_col); → accelerates:
- Containment
jsonb_col @> '{"k":"v"}'
- Key existence
jsonb_col ? 'k', any/all keys ?\|, ?&
- Path containment on nested docs
- Disjunction
jsonb_col @> ANY(ARRAY['{"status":"active"}', '{"status":"pending"}'])
- Heavy
@> workloads: consider opclass jsonb_path_ops for smaller/faster containment-only indexes:
CREATE INDEX ON tbl USING GIN (jsonb_col jsonb_path_ops);
- Trade-off: loses support for key existence (
?, ?|, ?&) queries—only supports containment (@>)
- Equality/range on a specific scalar field: extract and index with B-tree (generated column or expression):
ALTER TABLE tbl ADD COLUMN price INT GENERATED ALWAYS AS ((jsonb_col->>'price')::INT) STORED;
CREATE INDEX ON tbl (price);
- Prefer queries like
WHERE price BETWEEN 100 AND 500 (uses B-tree) over WHERE (jsonb_col->>'price')::INT BETWEEN 100 AND 500 without index.
- Arrays inside JSONB: use GIN +
@> for containment (e.g., tags). Consider jsonb_path_ops if only doing containment.
- Keep core relations in tables; use JSONB for optional/variable attributes.
- Use constraints to limit allowed JSONB values in a column e.g.
config JSONB NOT NULL CHECK(jsonb_typeof(config) = 'object')
Common Patterns
UPSERT:
INSERT INTO settings (user_id, key, value)
VALUES (123, 'theme', 'dark')
ON CONFLICT (user_id, key)
DO UPDATE SET value = EXCLUDED.value;
Cursor Pagination:
SELECT * FROM products WHERE id > $last_id ORDER BY id LIMIT 20;
-- O(1) vs OFFSET which is O(n)
Queue Processing:
UPDATE jobs SET status = 'processing'
WHERE id = (
SELECT id FROM jobs WHERE status = 'pending'
ORDER BY created_at LIMIT 1
FOR UPDATE SKIP LOCKED
) RETURNING *;
Anti-Pattern Detection
-- Find unindexed foreign keys
SELECT conrelid::regclass, a.attname
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)
);
-- Find slow queries
SELECT query, mean_exec_time, calls
FROM pg_stat_statements
WHERE mean_exec_time > 100
ORDER BY mean_exec_time DESC;
-- Check table bloat
SELECT relname, n_dead_tup, last_vacuum
FROM pg_stat_user_tables
WHERE n_dead_tup > 1000
ORDER BY n_dead_tup DESC;
Configuration Template
-- Connection limits (adjust for RAM)
ALTER SYSTEM SET max_connections = 100;
ALTER SYSTEM SET work_mem = '8MB';
-- Timeouts
ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';
ALTER SYSTEM SET statement_timeout = '30s';
-- Monitoring
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Security defaults
REVOKE ALL ON SCHEMA public FROM public;
SELECT pg_reload_conf();
Extensions
pgcrypto: crypt() for password hashing.
uuid-ossp: alternative UUID functions; prefer pgcrypto for new projects.
pg_trgm: fuzzy text search with % operator, similarity() function. Index with GIN for LIKE '%pattern%' acceleration.
citext: case-insensitive text type. Prefer expression indexes on LOWER(col) unless you need case-insensitive constraints.
btree_gin/btree_gist: enable mixed-type indexes (e.g., GIN index on both JSONB and text columns).
hstore: key-value pairs; mostly superseded by JSONB but useful for simple string mappings.
timescaledb: essential for time-series—automated partitioning, retention, compression, continuous aggregates. Self-hosted and on Tiger Cloud.
postgis: comprehensive geospatial support beyond basic geometric types—essential for location-based applications.
pgvector: vector similarity search for embeddings.
pgaudit: audit logging for all database activity.
Examples
Users
CREATE TABLE users (
user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX ON users (LOWER(email));
CREATE INDEX ON users (created_at);
Orders
CREATE TABLE orders (
order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(user_id),
status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','PAID','CANCELED')),
total NUMERIC(10,2) NOT NULL CHECK (total > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON orders (user_id);
CREATE INDEX ON orders (created_at);
JSONB
CREATE TABLE profiles (
user_id BIGINT PRIMARY KEY REFERENCES users(user_id),
attrs JSONB NOT NULL DEFAULT '{}',
theme TEXT GENERATED ALWAYS AS (attrs->>'theme') STORED
);
CREATE INDEX profiles_attrs_gin ON profiles USING GIN (attrs);
Related Resources
- Agent:
database-reviewer - Full database review workflow
- dhamaniasad/awesome-postgres — Curated list of PostgreSQL software, libraries, tools, and resources (11,759+ GitHub stars, CC0-1.0)
Credits
- Supabase Agent Skills (MIT License) — performance rules and patterns
- postgres-schema-design — table design reference (Apache 2.0)
- awesome-postgres by BytesAgain / dhamaniasad — resource curation (CC0-1.0)
1---2name: postgres-best-practices3description: Comprehensive PostgreSQL reference covering performance optimization, schema design, indexing, query patterns, connection management, security, and advanced features. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, migrations, or database configurations.4---56# PostgreSQL Best Practices78Comprehensive PostgreSQL reference consolidating performance optimization (Supabase), common patterns, and schema design guidance. Covers 8 rule categories prioritized by impact, plus detailed data type and table design reference.910## When to Use1112Reference these guidelines when:13- Writing SQL queries, migrations, or designing schemas14- Implementing indexes or query optimization15- Reviewing database performance issues16- Configuring connection pooling or scaling17- Optimizing for Postgres-specific features18- Working with Row-Level Security (RLS)19- Choosing data types, constraints, or table structures20- Troubleshooting slow queries2122## Rule Categories by Priority2324| Priority | Category | Impact | Prefix |25|----------|----------|--------|--------|26| 1 | Query Performance | CRITICAL | `query-` |27| 2 | Connection Management | CRITICAL | `conn-` |28| 3 | Security & RLS | CRITICAL | `security-` |29| 4 | Schema Design | HIGH | `schema-` |30| 5 | Concurrency & Locking | MEDIUM-HIGH | `lock-` |31| 6 | Data Access Patterns | MEDIUM | `data-` |32| 7 | Monitoring & Diagnostics | LOW-MEDIUM | `monitor-` |33| 8 | Advanced Features | LOW | `advanced-` |3435## Detailed Rule Files3637Read individual rule files for detailed explanations and SQL examples:3839```40rules/query-missing-indexes.md41rules/schema-partial-indexes.md42rules/_sections.md43```4445Each rule file contains:46- Brief explanation of why it matters47- Incorrect SQL example with explanation48- Correct SQL example with explanation49- Optional EXPLAIN output or metrics50- Additional context and references51- Supabase-specific notes (when applicable)5253For the complete compiled guide with all rules expanded: `AGENTS.md`5455---5657## Schema Design: Core Rules5859- Define a **PRIMARY KEY** for reference tables (users, orders, etc.). Not always needed for time-series/event/log data. When used, prefer `BIGINT GENERATED ALWAYS AS IDENTITY`; use `UUID` only when global uniqueness/opacity is needed.60- **Normalize first (to 3NF)** to eliminate data redundancy and update anomalies; denormalize **only** for measured, high-ROI reads where join performance is proven problematic. Premature denormalization creates maintenance burden.61- Add **NOT NULL** everywhere it's semantically required; use **DEFAULT**s for common values.62- Create **indexes for access paths you actually query**: PK/unique (auto), **FK columns (manual!)**, frequent filters/sorts, and join keys.63- Prefer **TIMESTAMPTZ** for event time; **NUMERIC** for money; **TEXT** for strings; **BIGINT** for integer values, **DOUBLE PRECISION** for floats (or `NUMERIC` for exact decimal arithmetic).6465## PostgreSQL "Gotchas"6667- **Identifiers**: unquoted → lowercased. Avoid quoted/mixed-case names. Convention: use `snake_case` for table/column names.68- **Unique + NULLs**: UNIQUE allows multiple NULLs. Use `UNIQUE (...) NULLS NOT DISTINCT` (PG15+) to restrict to one NULL.69- **FK indexes**: PostgreSQL **does not** auto-index FK columns. Add them.70- **No silent coercions**: length/precision overflows error out (no truncation). Example: inserting 999 into `NUMERIC(2,0)` fails with error, unlike some databases that silently truncate or round.71- **Sequences/identity have gaps** (normal; don't "fix"). Rollbacks, crashes, and concurrent transactions create gaps in ID sequences (1, 2, 5, 6...). This is expected behavior—don't try to make IDs consecutive.72- **Heap storage**: no clustered PK by default (unlike SQL Server/MySQL InnoDB); `CLUSTER` is one-off reorganization, not maintained on subsequent inserts. Row order on disk is insertion order unless explicitly clustered.73- **MVCC**: updates/deletes leave dead tuples; vacuum handles them—design to avoid hot wide-row churn.7475## Data Types7677- **IDs**: `BIGINT GENERATED ALWAYS AS IDENTITY` preferred (`GENERATED BY DEFAULT` also fine); `UUID` when merging/federating/used in a distributed system or for opaque IDs. Generate with `uuidv7()` (preferred if using PG18+) or `gen_random_uuid()` (if using an older PG version).78- **Integers**: prefer `BIGINT` unless storage space is critical; `INTEGER` for smaller ranges; avoid `SMALLINT` unless constrained.79- **Floats**: prefer `DOUBLE PRECISION` over `REAL` unless storage space is critical. Use `NUMERIC` for exact decimal arithmetic.80- **Strings**: prefer `TEXT`; if length limits needed, use `CHECK (LENGTH(col) <= n)` instead of `VARCHAR(n)`; avoid `CHAR(n)`. Use `BYTEA` for binary data. Large strings/binary (>2KB default threshold) automatically stored in TOAST with compression. TOAST storage: `PLAIN` (no TOAST), `EXTENDED` (compress + out-of-line), `EXTERNAL` (out-of-line, no compress), `MAIN` (compress, keep in-line if possible). Default `EXTENDED` usually optimal. Control with `ALTER TABLE tbl ALTER COLUMN col SET STORAGE strategy` and `ALTER TABLE tbl SET (toast_tuple_target = 4096)` for threshold. Case-insensitive: for locale/accent handling use non-deterministic collations; for plain ASCII use expression indexes on `LOWER(col)` (preferred unless column needs case-insensitive PK/FK/UNIQUE) or `CITEXT`.81- **Money**: `NUMERIC(p,s)` (never float).82- **Time**: `TIMESTAMPTZ` for timestamps; `DATE` for date-only; `INTERVAL` for durations. Avoid `TIMESTAMP` (without timezone). Use `now()` for transaction start time, `clock_timestamp()` for current wall-clock time.83- **Booleans**: `BOOLEAN` with `NOT NULL` constraint unless tri-state values are required.84- **Enums**: `CREATE TYPE ... AS ENUM` for small, stable sets (e.g. US states, days of week). For business-logic-driven and evolving values (e.g. order statuses) → use TEXT (or INT) + CHECK or lookup table.85- **Arrays**: `TEXT[]`, `INTEGER[]`, etc. Use for ordered lists where you query elements. Index with **GIN** for containment (`@>`, `<@`) and overlap (`&&`) queries. Access: `arr[1]` (1-indexed), `arr[1:3]` (slicing). Good for tags, categories; avoid for relations—use junction tables instead. Literal syntax: `'{val1,val2}'` or `ARRAY[val1,val2]`.86- **Range types**: `daterange`, `numrange`, `tstzrange` for intervals. Support overlap (`&&`), containment (`@>`), operators. Index with **GiST**. Good for scheduling, versioning, numeric ranges. Pick a bounds scheme and use it consistently; prefer `[)` (inclusive/exclusive) by default.87- **Network types**: `INET` for IP addresses, `CIDR` for network ranges, `MACADDR` for MAC addresses. Support network operators (`<<`, `>>`, `&&`).88- **Geometric types**: `POINT`, `LINE`, `POLYGON`, `CIRCLE` for 2D spatial data. Index with **GiST**. Consider **PostGIS** for advanced spatial features.89- **Text search**: `TSVECTOR` for full-text search documents, `TSQUERY` for search queries. Index `tsvector` with **GIN**. Always specify language: `to_tsvector('english', col)` and `to_tsquery('english', 'query')`. Never use single-argument versions. This applies to both index expressions and queries.90- **Domain types**: `CREATE DOMAIN email AS TEXT CHECK (VALUE ~ '^[^@]+@[^@]+$')` for reusable custom types with validation. Enforces constraints across tables.91- **Composite types**: `CREATE TYPE address AS (street TEXT, city TEXT, zip TEXT)` for structured data within columns. Access with `(col).field` syntax.92- **JSONB**: preferred over JSON; index with **GIN**. Use only for optional/semi-structured attrs. ONLY use JSON if the original ordering of the contents MUST be preserved.93- **Vector types**: `vector` type by `pgvector` for vector similarity search for embeddings.9495### Do Not Use These Data Types9697- DO NOT use `timestamp` (without time zone); DO use `timestamptz` instead.98- DO NOT use `char(n)` or `varchar(n)`; DO use `text` instead.99- DO NOT use `money` type; DO use `numeric` instead.100- DO NOT use `timetz` type; DO use `timestamptz` instead.101- DO NOT use `timestamptz(0)` or any other precision specification; DO use `timestamptz` instead.102- DO NOT use `serial` type; DO use `generated always as identity` instead.103104### Data Type Quick Reference105106| Use Case | Correct Type | Avoid |107|----------|-------------|-------|108| IDs | `bigint` | `int`, random UUID |109| Strings | `text` | `varchar(255)` |110| Timestamps | `timestamptz` | `timestamp` |111| Money | `numeric(10,2)` | `float` |112| Flags | `boolean` | `varchar`, `int` |113114## Table Types115116- **Regular**: default; fully durable, logged.117- **TEMPORARY**: session-scoped, auto-dropped, not logged. Faster for scratch work.118- **UNLOGGED**: persistent but not crash-safe. Faster writes; good for caches/staging.119120## Constraints121122- **PK**: implicit UNIQUE + NOT NULL; creates a B-tree index.123- **FK**: specify `ON DELETE/UPDATE` action (`CASCADE`, `RESTRICT`, `SET NULL`, `SET DEFAULT`). Add explicit index on referencing column—speeds up joins and prevents locking issues on parent deletes/updates. Use `DEFERRABLE INITIALLY DEFERRED` for circular FK dependencies checked at transaction end.124- **UNIQUE**: creates a B-tree index; allows multiple NULLs unless `NULLS NOT DISTINCT` (PG15+). Standard behavior: `(1, NULL)` and `(1, NULL)` are allowed. With `NULLS NOT DISTINCT`: only one `(1, NULL)` allowed. Prefer `NULLS NOT DISTINCT` unless you specifically need duplicate NULLs.125- **CHECK**: row-local constraints; NULL values pass the check (three-valued logic). Example: `CHECK (price > 0)` allows NULL prices. Combine with `NOT NULL` to enforce: `price NUMERIC NOT NULL CHECK (price > 0)`.126- **EXCLUDE**: prevents overlapping values using operators. `EXCLUDE USING gist (room_id WITH =, booking_period WITH &&)` prevents double-booking rooms. Requires appropriate index type (often GiST).127128## Indexing129130### Index Type Reference131132| Query Pattern | Index Type | Example |133|--------------|------------|---------|134| `WHERE col = value` | B-tree (default) | `CREATE INDEX idx ON t (col)` |135| `WHERE col > value` | B-tree | `CREATE INDEX idx ON t (col)` |136| `WHERE a = x AND b > y` | Composite | `CREATE INDEX idx ON t (a, b)` |137| `WHERE jsonb @> '{}'` | GIN | `CREATE INDEX idx ON t USING gin (col)` |138| `WHERE tsv @@ query` | GIN | `CREATE INDEX idx ON t USING gin (col)` |139| Time-series ranges | BRIN | `CREATE INDEX idx ON t USING brin (col)` |140141### Index Types Explained142143- **B-tree**: default for equality/range queries (`=`, `<`, `>`, `BETWEEN`, `ORDER BY`)144- **Composite**: order matters—index used if equality on leftmost prefix (`WHERE a = ? AND b > ?` uses index on `(a,b)`, but `WHERE b = ?` does not). Put most selective/frequently filtered columns first.145- **Covering**: `CREATE INDEX ON tbl (id) INCLUDE (name, email)` - includes non-key columns for index-only scans without visiting table.146- **Partial**: for hot subsets (`WHERE status = 'active'` → `CREATE INDEX ON tbl (user_id) WHERE status = 'active'`). Any query with `status = 'active'` can use this index.147- **Expression**: for computed search keys (`CREATE INDEX ON tbl (LOWER(email))`). Expression must match exactly in WHERE clause: `WHERE LOWER(email) = 'user@example.com'`.148- **GIN**: JSONB containment/existence, arrays (`@>`, `?`), full-text search (`@@`)149- **GiST**: ranges, geometry, exclusion constraints150- **BRIN**: very large, naturally ordered data (time-series)—minimal storage overhead. Effective when row order on disk correlates with indexed column (insertion order or after `CLUSTER`).151152### Common Index Patterns153154**Composite Index Order:**155```sql156-- Equality columns first, then range columns157CREATE INDEX idx ON orders (status, created_at);158-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'159```160161**Covering Index:**162```sql163CREATE INDEX idx ON users (email) INCLUDE (name, created_at);164-- Avoids table lookup for SELECT email, name, created_at165```166167**Partial Index:**168```sql169CREATE INDEX idx ON users (email) WHERE deleted_at IS NULL;170-- Smaller index, only includes active users171```172173## Row-Level Security174175Enable with `ALTER TABLE tbl ENABLE ROW LEVEL SECURITY`. Create policies: `CREATE POLICY user_access ON orders FOR SELECT TO app_users USING (user_id = current_user_id())`. Built-in user-based access control at the row level.176177**Optimized RLS Policy:**178```sql179CREATE POLICY policy ON orders180 USING ((SELECT auth.uid()) = user_id); -- Wrap in SELECT!181```182183## Partitioning184185- Use for very large tables (>100M rows) where queries consistently filter on partition key (often time/date).186- Alternate use: use for tables where data maintenance tasks dictates e.g. data pruned or bulk replaced periodically187- **RANGE**: common for time-series (`PARTITION BY RANGE (created_at)`). Create partitions: `CREATE TABLE logs_2024_01 PARTITION OF logs FOR VALUES FROM ('2024-01-01') TO ('2024-02-01')`. **TimescaleDB** automates time-based or ID-based partitioning with retention policies and compression.188- **LIST**: for discrete values (`PARTITION BY LIST (region)`). Example: `FOR VALUES IN ('us-east', 'us-west')`.189- **HASH**: for even distribution when no natural key (`PARTITION BY HASH (user_id)`). Creates N partitions with modulus.190- **Constraint exclusion**: requires `CHECK` constraints on partitions for query planner to prune. Auto-created for declarative partitioning (PG10+).191- Prefer declarative partitioning or hypertables. Do NOT use table inheritance.192- **Limitations**: no global UNIQUE constraints—include partition key in PK/UNIQUE. FKs from partitioned tables not supported; use triggers.193194## Special Considerations195196### Update-Heavy Tables197198- **Separate hot/cold columns**—put frequently updated columns in separate table to minimize bloat.199- **Use `fillfactor=90`** to leave space for HOT updates that avoid index maintenance.200- **Avoid updating indexed columns**—prevents beneficial HOT updates.201- **Partition by update patterns**—separate frequently updated rows in a different partition from stable data.202203### Insert-Heavy Workloads204205- **Minimize indexes**—only create what you query; every index slows inserts.206- **Use `COPY` or multi-row `INSERT`** instead of single-row inserts.207- **UNLOGGED tables** for rebuildable staging data—much faster writes.208- **Defer index creation** for bulk loads—>drop index, load data, recreate indexes.209- **Partition by time/hash** to distribute load. **TimescaleDB** automates partitioning and compression of insert-heavy data.210- **Use a natural key for primary key** such as a (timestamp, device_id) if enforcing global uniqueness is important many insert-heavy tables don't need a primary key at all.211- If you do need a surrogate key, **Prefer `BIGINT GENERATED ALWAYS AS IDENTITY` over `UUID`**.212213### Upsert-Friendly Design214215- **Requires UNIQUE index** on conflict target columns—`ON CONFLICT (col1, col2)` needs exact matching unique index (partial indexes don't work).216- **Use `EXCLUDED.column`** to reference would-be-inserted values; only update columns that actually changed to reduce write overhead.217- **`DO NOTHING` faster** than `DO UPDATE` when no actual update needed.218219### Safe Schema Evolution220221- **Transactional DDL**: most DDL operations can run in transactions and be rolled back—`BEGIN; ALTER TABLE...; ROLLBACK;` for safe testing.222- **Concurrent index creation**: `CREATE INDEX CONCURRENTLY` avoids blocking writes but can't run in transactions.223- **Volatile defaults cause rewrites**: adding `NOT NULL` columns with volatile defaults (e.g., `now()`, `gen_random_uuid()`) rewrites entire table. Non-volatile defaults are fast.224- **Drop constraints before columns**: `ALTER TABLE DROP CONSTRAINT` then `DROP COLUMN` to avoid dependency issues.225- **Function signature changes**: `CREATE OR REPLACE` with different arguments creates overloads, not replacements. DROP old version if no overload desired.226227## Generated Columns228229- `... GENERATED ALWAYS AS (<expr>) STORED` for computed, indexable fields. PG18+ adds `VIRTUAL` columns (computed on read, not stored).230231## JSONB Guidance232233- Prefer `JSONB` with **GIN** index.234- Default: `CREATE INDEX ON tbl USING GIN (jsonb_col);` → accelerates:235 - **Containment** `jsonb_col @> '{"k":"v"}'`236 - **Key existence** `jsonb_col ? 'k'`, **any/all keys** `?\|`, `?&`237 - **Path containment** on nested docs238 - **Disjunction** `jsonb_col @> ANY(ARRAY['{"status":"active"}', '{"status":"pending"}'])`239- Heavy `@>` workloads: consider opclass `jsonb_path_ops` for smaller/faster containment-only indexes:240 - `CREATE INDEX ON tbl USING GIN (jsonb_col jsonb_path_ops);`241 - **Trade-off**: loses support for key existence (`?`, `?|`, `?&`) queries—only supports containment (`@>`)242- Equality/range on a specific scalar field: extract and index with B-tree (generated column or expression):243 - `ALTER TABLE tbl ADD COLUMN price INT GENERATED ALWAYS AS ((jsonb_col->>'price')::INT) STORED;`244 - `CREATE INDEX ON tbl (price);`245 - Prefer queries like `WHERE price BETWEEN 100 AND 500` (uses B-tree) over `WHERE (jsonb_col->>'price')::INT BETWEEN 100 AND 500` without index.246- Arrays inside JSONB: use GIN + `@>` for containment (e.g., tags). Consider `jsonb_path_ops` if only doing containment.247- Keep core relations in tables; use JSONB for optional/variable attributes.248- Use constraints to limit allowed JSONB values in a column e.g. `config JSONB NOT NULL CHECK(jsonb_typeof(config) = 'object')`249250## Common Patterns251252**UPSERT:**253```sql254INSERT INTO settings (user_id, key, value)255VALUES (123, 'theme', 'dark')256ON CONFLICT (user_id, key)257DO UPDATE SET value = EXCLUDED.value;258```259260**Cursor Pagination:**261```sql262SELECT * FROM products WHERE id > $last_id ORDER BY id LIMIT 20;263-- O(1) vs OFFSET which is O(n)264```265266**Queue Processing:**267```sql268UPDATE jobs SET status = 'processing'269WHERE id = (270 SELECT id FROM jobs WHERE status = 'pending'271 ORDER BY created_at LIMIT 1272 FOR UPDATE SKIP LOCKED273) RETURNING *;274```275276## Anti-Pattern Detection277278```sql279-- Find unindexed foreign keys280SELECT conrelid::regclass, a.attname281FROM pg_constraint c282JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)283WHERE c.contype = 'f'284 AND NOT EXISTS (285 SELECT 1 FROM pg_index i286 WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)287 );288289-- Find slow queries290SELECT query, mean_exec_time, calls291FROM pg_stat_statements292WHERE mean_exec_time > 100293ORDER BY mean_exec_time DESC;294295-- Check table bloat296SELECT relname, n_dead_tup, last_vacuum297FROM pg_stat_user_tables298WHERE n_dead_tup > 1000299ORDER BY n_dead_tup DESC;300```301302## Configuration Template303304```sql305-- Connection limits (adjust for RAM)306ALTER SYSTEM SET max_connections = 100;307ALTER SYSTEM SET work_mem = '8MB';308309-- Timeouts310ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';311ALTER SYSTEM SET statement_timeout = '30s';312313-- Monitoring314CREATE EXTENSION IF NOT EXISTS pg_stat_statements;315316-- Security defaults317REVOKE ALL ON SCHEMA public FROM public;318319SELECT pg_reload_conf();320```321322## Extensions323324- **`pgcrypto`**: `crypt()` for password hashing.325- **`uuid-ossp`**: alternative UUID functions; prefer `pgcrypto` for new projects.326- **`pg_trgm`**: fuzzy text search with `%` operator, `similarity()` function. Index with GIN for `LIKE '%pattern%'` acceleration.327- **`citext`**: case-insensitive text type. Prefer expression indexes on `LOWER(col)` unless you need case-insensitive constraints.328- **`btree_gin`/`btree_gist`**: enable mixed-type indexes (e.g., GIN index on both JSONB and text columns).329- **`hstore`**: key-value pairs; mostly superseded by JSONB but useful for simple string mappings.330- **`timescaledb`**: essential for time-series—automated partitioning, retention, compression, continuous aggregates. Self-hosted and on Tiger Cloud.331- **`postgis`**: comprehensive geospatial support beyond basic geometric types—essential for location-based applications.332- **`pgvector`**: vector similarity search for embeddings.333- **`pgaudit`**: audit logging for all database activity.334335## Examples336337### Users338339```sql340CREATE TABLE users (341 user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,342 email TEXT NOT NULL UNIQUE,343 name TEXT NOT NULL,344 created_at TIMESTAMPTZ NOT NULL DEFAULT now()345);346CREATE UNIQUE INDEX ON users (LOWER(email));347CREATE INDEX ON users (created_at);348```349350### Orders351352```sql353CREATE TABLE orders (354 order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,355 user_id BIGINT NOT NULL REFERENCES users(user_id),356 status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','PAID','CANCELED')),357 total NUMERIC(10,2) NOT NULL CHECK (total > 0),358 created_at TIMESTAMPTZ NOT NULL DEFAULT now()359);360CREATE INDEX ON orders (user_id);361CREATE INDEX ON orders (created_at);362```363364### JSONB365366```sql367CREATE TABLE profiles (368 user_id BIGINT PRIMARY KEY REFERENCES users(user_id),369 attrs JSONB NOT NULL DEFAULT '{}',370 theme TEXT GENERATED ALWAYS AS (attrs->>'theme') STORED371);372CREATE INDEX profiles_attrs_gin ON profiles USING GIN (attrs);373```374375## Related Resources376377- Agent: `database-reviewer` - Full database review workflow378- [dhamaniasad/awesome-postgres](https://github.com/dhamaniasad/awesome-postgres) — Curated list of PostgreSQL software, libraries, tools, and resources (11,759+ GitHub stars, CC0-1.0)379380## Credits381382- Supabase Agent Skills (MIT License) — performance rules and patterns383- postgres-schema-design — table design reference (Apache 2.0)384- awesome-postgres by BytesAgain / dhamaniasad — resource curation (CC0-1.0)