Two notes for Postgres:
- This note → using Postgres: SQL, types, schema, transactions, indexes, query plans, app side.
- PostgreSQL Internals and Operations → how it stores data and how to run it: pages, WAL, vacuum, config, security, backup, replication, monitoring.
Theory that is not Postgres specific (B-Tree, LSM, ACID, CAP) lives in Database internal.
│ ├── 1. Architecture & psql
│ ├── 2. SQL you actually use
│ ├── 3. Data types, JSONB, arrays & ranges
│ ├── 4. Schema design & safe migrations
│ ├── 5. Functions, views & triggers
│ ├── 6. Transactions, MVCC & locks
│ ├── 7. Indexing
│ ├── 8. Query planning & performance
│ ├── 9. Application development
│ └── 10. Search & extensions
│
└── PostgreSQL Internals and Operations
├── 1. Storage: pages & tuples
├── 2. WAL & crash recovery
├── 3. Vacuum, bloat & XID wraparound
├── 4. Configuration
├── 5. Security, roles & RLS
├── 6. Backup & PITR
├── 7. Replication, HA & scaling
├── 8. Monitoring & incident response
└── 9. Upgrades
1. Architecture & psql
In nutshell → one postmaster process listens on 5432 and forks a new process for every connection. All processes talk through shared memory.
flowchart TB
App1[App instance 1] --> PGB
App2[App instance 2] --> PGB
PGB["PgBouncer (optional pooler)"] --> PM
subgraph Server["PostgreSQL server"]
PM["Postmaster :5432"] -- "fork per connection" --> B1[Backend 1]
PM -- fork --> B2[Backend 2]
PM -- fork --> B3[Backend 3]
subgraph SHM["Shared memory"]
SB["shared_buffers (8KB pages cache)"]
WB[WAL buffers]
LT[Lock table]
end
B1 <--> SHM
B2 <--> SHM
B3 <--> SHM
subgraph BG["Background processes"]
CP[Checkpointer]
BW[Background writer]
WW[WAL writer]
AV[Autovacuum workers]
WS[WAL sender]
end
BG <--> SHM
end
SB -- "dirty pages, later" --> DF[("Data files base/")]
WB -- "on COMMIT, fsync" --> WAL[("pg_wal/")]
WS -- "WAL stream" --> R[(Replica)]
- Postmaster → parent process, accepts connection and forks a backend.
- Backend process → one per client. Parses, plans and executes your queries.
- Background processes → checkpointer, background writer, WAL writer, autovacuum launcher + workers, WAL sender (replication).
- Shared memory →
shared_buffers(page cache), WAL buffers, lock table. This is how the processes share state.
Why process and not thread
- Fault tolerance: one backend crash won’t corrupt others’ memory (in threads it would).
- Cost: each backend is a few MB of RAM + fork cost → default
max_connections = 100. That’s why people put PgBouncer in front (see section 9).
Everything is append → even an UPDATE writes a new row version, old one becomes dead and vacuum cleans it later (section 6).
How a query runs
flowchart LR
Q[SQL text] --> P["Parser (syntax check, parse tree)"]
P --> RW["Rewriter (expand views, rules)"]
RW --> PL["Planner (uses pg_stats, picks cheapest plan)"]
PL --> EX["Executor (runs plan nodes, reads pages)"]
EX --> RES[Rows to client]
SELECT pid, usename, state, query FROM pg_stat_activity; -- -> one row per backend process
SHOW max_connections;
SHOW shared_buffers;psql commands you’ll use daily
\l -> list databases
\c shop -> connect to db
\dt -> list tables
\d orders -> describe table (columns, indexes, FKs)
\di -> list indexes
\x -> expanded output for wide rows
\timing -> show query time
\e -> open query in editor2. SQL we actually use
Tables used in examples: users(id, name, email), orders(id, user_id, amount, status, created_at)
Logical order of execution (not the order you write it)
flowchart LR
A[FROM / JOIN] --> B[WHERE] --> C[GROUP BY] --> D[HAVING] --> E[SELECT] --> F[DISTINCT] --> G[ORDER BY] --> H[LIMIT]
That’s why we can’t use a SELECT alias inside WHERE but can in ORDER BY.
Joins
| Join | Returns |
|---|---|
INNER JOIN | only matching rows on both sides |
LEFT JOIN | all left rows, NULLs where right has no match |
FULL JOIN | all rows from both, NULLs where no match |
CROSS JOIN | every combination (rarely what you want) |
JOIN LATERAL | subquery that can use columns of the left row (top-N per group) |
-- users with no orders (anti join)
SELECT u.* FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);Aggregation
SELECT user_id,
count(*) AS total,
count(*) FILTER (WHERE status = 'paid') AS paid, -- -> conditional count without CASE
sum(amount)
FROM orders
GROUP BY user_id
HAVING sum(amount) > 1000; -- -> HAVING filters groups, WHERE filters rowsCTE & recursive CTE
CTE = named subquery, makes long queries readable. Since PG12 the planner inlines it (no perf penalty) unless we write MATERIALIZED.
-- org chart: everyone under manager 1
WITH RECURSIVE team AS (
SELECT id, name, manager_id FROM employees WHERE id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e JOIN team t ON e.manager_id = t.id
)
SELECT * FROM team;Window functions
Aggregate without collapsing rows. OVER (PARTITION BY ... ORDER BY ...)
-- latest order per user
SELECT * FROM (
SELECT o.*, row_number() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM orders o
) x WHERE rn = 1;
-- running total + previous order amount
SELECT id, amount,
sum(amount) OVER (PARTITION BY user_id ORDER BY created_at) AS running_total,
lag(amount) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_amount
FROM orders;row_number → 1,2,3 | rank → 1,1,3 | dense_rank → 1,1,2
Upsert & RETURNING
INSERT INTO users (email, name) VALUES ('a@x.com', 'A')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name -- -> EXCLUDED = the row you tried to insert
RETURNING id; -- -> get the id back without a second queryNULL traps
NULL = NULL→ NULL (not true). UseIS NULLorIS DISTINCT FROM.NOT IN (subquery)where subquery has a NULL → returns zero rows. UseNOT EXISTS.count(*)counts rows,count(col)skips NULLs.sumof no rows → NULL, not 0. Usecoalesce(sum(amount), 0).
3. Data types, JSONB, arrays & ranges
In nutshell → the type decides disk size, index size, which bad values the DB rejects for us, and how painful a change is later (most type changes rewrite the whole table under a lock). Pick right on day one.
Quick pick
| Need | Use | Avoid |
|---|---|---|
| id | bigint GENERATED ALWAYS AS IDENTITY | serial (old style), int (overflows at 2.1B) |
| public id | uuid (16 bytes), v7 if possible | uuid stored as text |
| string | text | char(n) (pads spaces) |
| money | numeric(12,2) or bigint cents | float, money |
| time | timestamptz | timestamp without tz |
| flexible fields | jsonb | json, EAV tables |
| fixed set of values | CHECK (status IN (...)) or lookup table | enum if values may be removed |
| IP address | inet / cidr | text |
| files | S3 + store the key as text | big bytea in the table |
How a row is stored under the hood
one row (tuple) inside an 8KB page
┌───────────────────────┬──────────────┬───────────────────────────────────┐
│ header 23 bytes │ null bitmap │ column data, each column aligned │
│ xmin xmax ctid flags │ 1 bit / col │ id | created_at | name | payload │
└───────────────────────┴──────────────┴───────────────────────────────────┘
header + bitmap padded to 24 bytes (multiple of 8)
- NULL costs no data bytes, only 1 bit in the null bitmap (bitmap exists only when the row has a NULL).
- Fixed size types (int, bigint, timestamptz, uuid…) stored inline and must start at an aligned address → padding bytes get added between columns.
- Variable length types (text, numeric, jsonb, arrays, bytea) = “varlena” (variable length). Their size changes per row, so Postgres stores the length in front of the value: 1 byte length header if value ≤ 126 bytes, 4 byte header otherwise.
'hello'in a text column = 1 + 5 = 6 bytes. - Every row also pays the 24 byte header → a table of tiny rows (2 ints) is mostly header. 100M rows × 24B = 2.4GB just headers.
| Type | Bytes | Aligned to |
|---|---|---|
boolean | 1 | 1 |
smallint | 2 | 2 |
integer, real, date | 4 | 4 |
bigint, double precision | 8 | 8 |
timestamp, timestamptz | 8 (µs since 2000-01-01) | 8 |
uuid | 16 | 1 |
interval | 16 | 8 |
numeric | ~2 bytes per 4 digits + header | 2 |
text, varchar, jsonb, arrays | 1 or 4 header + data | 4 (1 when short) |
Column tetris (alignment & padding)
In nutshell → the order we write columns in CREATE TABLE is the order they sit on disk. A bad order wastes empty bytes in every row.
Why there are empty bytes at all
- The CPU reads memory in chunks of 8 bytes. An 8 byte number is fastest (and on some CPUs only possible) to read when it starts at an address divisible by 8. This rule is called alignment.
- Postgres keeps a row on disk in exactly the same byte layout it uses in memory, so a page can be read from disk and used directly with no conversion. So the disk layout follows the CPU’s alignment rules too.
- Rule per type (the “Aligned to” column in the table above):
bigint/timestamptzmust start at an offset divisible by 8,int/dateby 4,smallintby 2.boolean,uuidand short text can start anywhere. - If the previous column ends at a position that breaks this rule, Postgres fills the gap with empty padding bytes.
Same 6 columns, two orders:
-- order A (written in "natural" order)
CREATE TABLE orders_a (id int, created_at timestamptz, is_paid boolean,
amount_cents bigint, status_code smallint, user_id bigint);
-- order B (8 byte columns first, then 4, 2, 1)
CREATE TABLE orders_b (created_at timestamptz, amount_cents bigint, user_id bigint,
id int, status_code smallint, is_paid boolean);Byte by byte (each cell = 1 byte, . = padding)
order A: 48 data bytes, 17 of them wasted
0 4 8 16 24 32 34 40 48
[id ][. . . ][created_at ][p . . . . . . ][amount_cents ][st][. . .][user_id ]
4 B 4 pad 8 B 1B 7 pad 8 B 2B 6 pad 8 B
▲ created_at must start at 8 ▲ amount must start at 24 ▲ user_id at 40
order B: 31 data bytes, 0 wasted
0 8 16 24 28 30 31
[created_at ][amount_cents ][user_id ][id ][st][p]
8 B 8 B 8 B 4 B 2B 1B
- In order A,
idends at byte 4, butcreated_atmust start at a multiple of 8 → 4 empty bytes. Same thing afteris_paid(7 empty) and afterstatus_code(6 empty). - In order B every column ends exactly where the next one is allowed to start → no gaps. Big ones first means each later (smaller) column always lands on an allowed position.
Measured on PG18:
SELECT pg_column_size(ROW(1::int, now(), true, 1::bigint, 1::smallint, 1::bigint)); -- -> 72 (24 header + 48)
SELECT pg_column_size(ROW(now(), 1::bigint, 1::bigint, 1::int, 1::smallint, true)); -- -> 55 (24 header + 31)
-- 1M rows each: orders_a = 73 MB, orders_b = 57 MB -> 22% smaller, just by reorderingSmaller rows = more rows per 8KB page = fewer pages to read, more of the table fits in RAM, smaller backups.
Ordering rule for CREATE TABLE
- 8 byte:
bigint,timestamptz,double precision(anduuid, 16 bytes but no alignment, fits anywhere) - 4 byte:
integer,date,real - 2 byte:
smallint - 1 byte:
boolean - variable length last:
text,numeric,jsonb, arrays → their size differs per row, so a fixed column placed after them lands on a different offset in each row and may need padding in some rows - Columns that are often NULL near the end. A NULL takes no bytes, so it doesn’t matter much, but it keeps the fixed columns at fixed positions
When it matters → tables with tens of millions of rows (events, logs, orders). For a 10k row settings table, write columns in whatever order reads best. Postgres can’t reorder columns later (ALTER TABLE always adds at the end), so changing it = create a new table and copy data → decide at create time.
TOAST (The Oversized-Attribute Storage Technique) → a row has to fit inside one 8KB page, and Postgres wants at least 4 rows per page. So when a row goes over ~2KB, Postgres shrinks it:
flowchart LR
R["Row > ~2KB"] --> C["Compress big values (pglz / lz4)"]
C --> Q{"Still > ~2KB?"}
Q -- no --> IN[Stored inline, compressed]
Q -- yes --> OUT["Move value to pg_toast table<br/>in ~2KB chunks"]
OUT --> P["Row keeps an 18 byte pointer"]
-
Reading a TOASTed column = extra lookups + decompress.
SELECT *on a table with big jsonb/text pulls all of it → select only the columns needed. -
Columns not touched by the query are not de-TOASTed → big values in their own column are cheap if we don’t select them.
SELECT pg_size_pretty(pg_relation_size('events')) AS main,
pg_size_pretty(pg_table_size('events') - pg_relation_size('events')) AS toast_and_maps,
pg_size_pretty(pg_indexes_size('events')) AS indexes;IDs
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEYserial= old shortcut that creates a sequence + default. Identity is the SQL standard version andALWAYSrefuses manual ids unlessOVERRIDING SYSTEM VALUE.- Mistake →
intprimary key on a fast growing table (events, logs). At 2,147,483,647 every insert fails. Fixing it =int -> bigintrewrite of the biggest table in the DB. bigint costs 4 extra bytes, always use it. - Mistake → importing rows with explicit ids into a
serialcolumn. Sequence doesn’t move → next normal insert getsduplicate key. Fix:
SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT max(id) FROM users));-
Sequences never roll back (rollback, failed insert, cache) → ids have gaps. Never use them as “gapless invoice numbers” → keep a counter row and
UPDATE ... RETURNINGit inside the transaction. -
Sequential ids in URLs leak how many users/orders we have and allow scraping
/users/1, /users/2...→ internalbigintPK + a publicuuidcolumn.
UUID
- Stored as 16 bytes. As
textit’s 37 bytes, slower to compare, and'ABC...'vs'abc...'become different values. - UUID v4 is random → each insert lands on a random B-tree page → page splits, index bloat, the index stops fitting in cache as the table grows.
- UUID v7 starts with a timestamp → inserts append to the end of the index like bigint.
uuidv7()is built in from PG18, before that generate v7 in the app.gen_random_uuid()= v4.
flowchart LR
subgraph V4["UUID v4 inserts"]
A1[new id] -.-> P1[page 3]
A2[new id] -.-> P2[page 91]
A3[new id] -.-> P3[page 40]
end
subgraph V7["UUID v7 / bigint inserts"]
B1[new id] --> L[last page]
B2[new id] --> L
B3[new id] --> L
end
Text
text,varchar,varchar(n)= same storage, same speed.varchar(n)only adds a length check.- Raising a
varchar(n)limit is instant, lowering it scans/rewrites. When the length rule matters usetext+CHECK (length(name) <= 100)→ easy to change later. char(n)pads with spaces up to n → wasted bytes and weird comparisons. Never.- Case-insensitive unique email →
CREATE UNIQUE INDEX ON users (lower(email));and always query withlower(email). Or thecitextextension. - Gotcha → text sort order and text indexes depend on the OS collation library (glibc / ICU). An OS upgrade that changes collation rules (glibc 2.28 did) can silently break index order → wrong query results.
REINDEXtext indexes after such upgrades. Postgres logs a collation version mismatch warning.
Numbers & money
numeric→ exact decimal, stored as base-10000 digits, slower math than ints. Right for money, rates, quantities.float/real→ approximate:
SELECT 0.1::float8 + 0.2::float8; -- -> 0.30000000000000004moneytype → formatting depends on server locale (lc_monetary), no currency stored. Avoid.bigintcents (amount_cents = 1999) → fast and exact, common in payment systems. Always storecurrencynext to it.numeric(5,2)rejects 1000.00 with an error instead of silently rounding → good, it catches bugs.
Time
timestamptzdoesn’t store a timezone. It converts input to UTC, stores 8 bytes, and shows it in the sessionTimeZone. Same size astimestamp.- Mistake →
timestamp(no tz) with app servers in different zones, or across DST changes → ambiguous values that can’t be fixed later. - Need the user’s original zone (“meeting at 9am Asia/Kolkata”)? Store the zone name in a separate
textcolumn. now()= transaction start time (same value for every row in the transaction).clock_timestamp()= real current time.datefor birthdays / business days,intervalfor durations (now() - interval '7 days').- Mistake →
WHERE date(created_at) = '2026-10-28'→ function on column, index oncreated_atnot used. Use a range:
WHERE created_at >= '2026-10-28' AND created_at < '2026-10-29'- Mistake →
BETWEEN '2026-10-01' AND '2026-10-31'on timestamptz misses everything after 00:00 on the 31st. Use>= start AND < next_start.
Boolean, status & enum
- Mistake → nullable boolean = 3 states (true / false / unknown). Use
boolean NOT NULL DEFAULT false. - Status column, 3 options:
| Option | Good | Bad |
|---|---|---|
text + CHECK (status IN (...)) | easy to change (drop + add constraint) | text bytes on every row |
enum | 4 bytes, sorts by declared order | ADD VALUE is easy, removing a value is not possible without recreating the type |
| lookup table + FK | can hold label, sort order, flags | one more join |
Other types worth knowing
-
inet/cidr→ IPs with operators:WHERE ip << '10.0.0.0/8' -
Domain → reusable type + rule:
CREATE DOMAIN email AS text CHECK (VALUE ~ '^[^@\s]+@[^@\s]+$'); -
Generated column →
total_cents bigint GENERATED ALWAYS AS (qty * price_cents) STORED. PG18 addsVIRTUAL(computed on read, no disk) and makes it the default. -
bytea→ small binary only. Files go to S3, DB stores the key. Big blobs bloat backups, replication and cache.
JSON vs JSONB
json→ stores the text as-is (keeps whitespace, duplicate keys, key order), parses on every read.jsonb→ parsed into a binary format on write. Can be indexed. Slightly slower write. Use jsonb.
Under the hood of jsonb
- On write: whitespace dropped, duplicate keys → last one wins, key order is not kept.
- Big documents (> ~2KB) get TOASTed (compressed, moved out of the row).
- Updating one key rewrites the whole document → new row version + new TOAST value. A counter inside a 50KB jsonb updated every second = 50KB written every second, plus WAL.
- Planner has no statistics inside jsonb → it guesses row counts for
payload->>'country' = 'IN'→ bad plans. An expression index fixes it (ANALYZE collects stats for indexed expressions), or promote the key to a real column.
SELECT payload->'user'->>'name' FROM events; -- -> `->` returns jsonb, `->>` returns text
SELECT * FROM events WHERE payload @> '{"type":"signup"}'; -- -> containment, uses GIN index
SELECT * FROM events WHERE payload ? 'coupon'; -- -> key exists
UPDATE events SET payload = jsonb_set(payload, '{status}', '"done"');
UPDATE events SET payload = payload - 'coupon'; -- -> remove keyIndexes on jsonb
CREATE INDEX ON events USING gin (payload); -- -> supports @>, ?, ?|, ?&
CREATE INDEX ON events USING gin (payload jsonb_path_ops); -- -> only @> (and jsonpath), smaller and faster
CREATE INDEX ON events ((payload->>'user_id')); -- -> B-tree on one key: =, <, >, ORDER BYMistakes
- Comparing numbers as text →
payload->>'price' > '10'is a text compare,'9' > '10'is true. Cast:(payload->>'price')::numeric > 10. - JSON null vs SQL NULL →
'{"a": null}'::jsonb -> 'a'is a jsonbnull(not SQL NULL).->>returns SQL NULL.IS NULLchecks behave differently on each. - Using jsonb to skip schema design → every reader must handle missing / renamed / wrongly typed keys forever. Good fit: external API payloads, user settings, sparse optional attributes. Bad fit: core fields we filter, join or sort on.
- jsonb can still have rules:
CHECK (payload ? 'type' AND jsonb_typeof(payload->'amount') = 'number')
Arrays
- Stored as one value (header + dimensions + elements). Changing one element rewrites the whole array. Big arrays get TOASTed.
- Index starts at 1, not 0:
tags[1]. - No FK on elements, no per-element uniqueness → if elements are other entities (user ids, product ids) use a join table.
- Good fit: small lists read with the row (tags, scores, feature flags).
CREATE TABLE posts (id bigint, tags text[]);
CREATE INDEX ON posts USING gin (tags);
SELECT * FROM posts WHERE tags @> ARRAY['pg']; -- -> uses GIN
SELECT * FROM posts WHERE 'pg' = ANY(tags); -- -> same result, but CAN'T use the GIN index
SELECT id, unnest(tags) AS tag FROM posts; -- -> one row per tag
SELECT user_id, array_agg(id ORDER BY id) FROM orders GROUP BY user_id; -- -> rows into arrayRanges
A range type holds start and end in one column. int4range, numrange, daterange, tstzrange. Multiranges (many ranges in one value) since PG14.
- Default bounds
[)→ includes start, excludes end.daterange('2026-01-01', '2026-01-05')= 1st to 4th. - Operators:
&&overlaps,@>contains,-|-adjacent. - Mistake → two columns
start_at,end_at+ overlap check in app code. Two requests at once both pass the check → double booking. Let the DB reject it:
CREATE EXTENSION btree_gist;
CREATE TABLE booking (
room_id int,
during tstzrange,
EXCLUDE USING gist (room_id WITH =, during WITH &&) -- -> same room + overlapping time = error
);No race condition possible here, the constraint is checked under the index lock.
4. Schema design & safe migrations
In nutshell → the schema is the set of rules our data can never break. App code changes every week, data lives for years and is written by many apps, scripts and people. Push the rules into the DB.
Creating tables properly
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE, -- -> safe to show in URLs
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
email text NOT NULL CHECK (length(email) <= 320),
name text NOT NULL,
plan text NOT NULL DEFAULT 'free' CHECK (plan IN ('free', 'pro'))
);
CREATE UNIQUE INDEX users_email_uq ON users (lower(email)); -- -> A@x.com and a@x.com are the same user
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
amount_cents bigint NOT NULL CHECK (amount_cents > 0),
created_at timestamptz NOT NULL DEFAULT now(),
currency text NOT NULL CHECK (length(currency) = 3),
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'paid', 'refunded')),
ship_address jsonb NOT NULL -- -> copy of address at order time
);
CREATE INDEX orders_user_created_idx ON orders (user_id, created_at); -- -> FK index + "latest orders of a user"
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);
CREATE TABLE order_tags ( -- -> many-to-many join table
order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
tag_id bigint NOT NULL REFERENCES tags (id) ON DELETE CASCADE,
PRIMARY KEY (order_id, tag_id) -- -> no duplicate pairs, covers lookups by order_id
);
CREATE INDEX ON order_tags (tag_id); -- -> covers lookups by tag_iderDiagram
users ||--o{ orders : places
orders ||--o{ order_tags : has
tags ||--o{ order_tags : labels
users {
bigint id PK
uuid public_id UK
timestamptz created_at
text email UK
text plan
}
orders {
bigint id PK
bigint user_id FK
bigint amount_cents
text status
jsonb ship_address
}
order_tags {
bigint order_id PK, FK
bigint tag_id PK, FK
}
tags {
bigint id PK
text name UK
}
Why each choice
NOT NULLon almost everything → NULL means “unknown”, not “empty”. Every nullable column is a 3-state value every query has to think about.- Constraint per business rule (
amount_cents > 0, allowed statuses) → a bug in any app, script or manualUPDATEgets rejected instead of stored. ON DELETE RESTRICTon orders → deleting a user who has orders fails instead of silently deleting money history.ON DELETE CASCADEonorder_tags→ rows that only exist because of the parent go with it.ship_addresscopied into the order → the order must show where it was shipped even after the user edits the profile. That’s a fact of the order, not duplication.- Column order: 8 byte columns first, then text/jsonb (column tetris, section 3).
Naming
- Unquoted names are folded to lowercase:
CREATE TABLE Userscreatesusers. - Mistake → quoted mixed case names (
"CreatedAt", often from ORMs). Now every raw query must write"CreatedAt"with quotes forever. Usesnake_case, and map names in the ORM. userandorderare reserved words → name tablesusers,orders.- Name constraints and indexes ourselves (
users_email_uq) → error messages and migrations become readable.
Schemas (namespaces)
- Cluster → database → schema → table. Default schema is
public.search_pathdecides which schema an unqualified name means. - Split modules or keep extensions apart:
CREATE SCHEMA billing; CREATE TABLE billing.invoices (...). - Since PG15 normal users can’t create objects in
publicby default → grant explicitly.
Keys
- Surrogate key (
bigintidentity) as PK +UNIQUEon the natural key (email, sku). - Mistake → natural key as PK (email, phone, username). They change → the change has to cascade into every FK in every table.
- Composite PK only for join tables (
(order_id, tag_id)).
Normalization
In nutshell → each fact is stored in one place.
- 1NF → one value per column (no
"pg,redis,kafka"text lists). - 2NF / 3NF → every non-key column depends on the key, the whole key, and nothing else (the user’s name lives in
users, not copied into every order). - Denormalize only for a measured read problem, and keep one source of truth: counter column updated in the same transaction, or a materialized view for reports (section 5).
Constraints in depth
- UNIQUE allows many NULLs (NULL ≠ NULL). Two users with
phone = NULLis fine, usually what we want. For “only one NULL” →UNIQUE NULLS NOT DISTINCT(PG15+). - Partial unique index → rule for a subset of rows:
-- only one active subscription per user, any number of cancelled ones
CREATE UNIQUE INDEX ON subscriptions (user_id) WHERE status = 'active';- CHECK only sees the current row. Rules across rows → UNIQUE / EXCLUDE constraint, or a trigger.
- Deferrable → checked at
COMMITinstead of per statement. Needed for swapping unique positions or circular FKs:
ALTER TABLE playlist_items ADD CONSTRAINT pos_uq UNIQUE (playlist_id, position) DEFERRABLE INITIALLY DEFERRED;- FK actions:
NO ACTION/RESTRICT(default, safe),CASCADE(only for owned children),SET NULL. - Gotcha →
CASCADEon a big tree: oneDELETE FROM userscan delete millions of rows across tables in one transaction, holding locks the whole time. - Gotcha → Postgres does not auto-create an index on the FK column (
orders.user_id). Without it, joins are slow and every delete/update onusersdoes a seq scan onordersto check for children. Always index FK columns.
-- FK columns without an index (leading column match)
SELECT c.conrelid::regclass AS table_name, a.attname AS fk_column
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]
);Common modeling mistakes
- Soft delete everywhere (
deleted_at) → every query must rememberWHERE deleted_at IS NULL, and a deleted user still blocks the email from signing up again. Fix: partial unique indexON users (lower(email)) WHERE deleted_at IS NULL, a view with only live rows, or move deleted rows to an archive table. - Polymorphic association (
commentable_type = 'post',commentable_id = 7) → no FK possible, orphans pile up. Fix: one nullable FK per parent + rule that exactly one is set:
CREATE TABLE comments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
post_id bigint REFERENCES posts (id),
photo_id bigint REFERENCES photos (id),
body text NOT NULL,
CHECK (num_nonnulls(post_id, photo_id) = 1)
);- EAV tables (
entity_id, attribute, value text) → every read is N self joins, no types, no constraints. Use ajsonbcolumn. - Comma separated lists in text → can’t index, join or validate. Use an array or a join table.
- Stored derived values without a rule (
totalcolumn next to line items) → drift apart. Use a generated column or compute it. - Multi-tenant tables without
tenant_idon child tables → can’t enforce isolation or use RLS. Puttenant_idon every table and first in composite indexes(tenant_id, created_at). - One hot row everyone updates (global counter, single settings row) → all writers queue on that row lock. Shard the counter (
nrows, sum on read) or count async. - Files in the DB → table, backups and replicas grow by GBs. S3 + key.
What ALTER TABLE does under the hood
A table’s definition lives in catalog tables (pg_class = tables, pg_attribute = columns, pg_constraint, pg_index). Some changes only edit the catalog (instant). Others rewrite every row into a new file (slow, needs 2× disk, locked the whole time).
| Change | Cost |
|---|---|
ADD COLUMN nullable, or with a non-volatile default ('free', now()) | catalog only, instant |
ADD COLUMN with a volatile default (gen_random_uuid(), clock_timestamp()) | full rewrite |
DROP COLUMN | catalog only. Space comes back only as rows get rewritten. Dropped columns still count toward the 1600 column limit |
RENAME COLUMN / RENAME TABLE | catalog only, but breaks every app still using the old name |
ALTER TYPE varchar(50) -> varchar(100) or -> text | catalog only |
ALTER TYPE int -> bigint, text -> int | full rewrite + rebuild every index |
SET NOT NULL | full scan (skipped if a validated CHECK (col IS NOT NULL) exists) |
ADD CHECK / ADD FOREIGN KEY | full scan (use NOT VALID + VALIDATE) |
CREATE INDEX | blocks writes for the whole build (use CONCURRENTLY) |
Even the instant ones need a short ACCESS EXCLUSIVE lock → lock queue problem below.
-- see the catalog ourselves
SELECT attname, atttypid::regtype, attnum, attisdropped
FROM pg_attribute WHERE attrelid = 'users'::regclass AND attnum > 0;Safe migrations on live big tables
Most ALTER TABLE takes an ACCESS EXCLUSIVE lock → blocks even SELECT. Worse, if it waits behind a long query, every query after it also waits (lock queue).
sequenceDiagram
participant R as Report query (60s)
participant T as users table
participant M as ALTER TABLE
participant A as App SELECTs
R->>T: ACCESS SHARE (running)
M->>T: wants ACCESS EXCLUSIVE
Note over M,T: waits for report to finish
A->>T: SELECT
Note over A,T: queued BEHIND the ALTER -> app is down for 60s
R-->>T: done
M-->>T: runs, releases
A-->>T: finally runs
So:
SET lock_timeout = '5s'; -- -> fail fast instead of blocking the whole app, then retry
CREATE INDEX CONCURRENTLY idx_orders_user ON orders (user_id); -- -> no write lock, can't run inside a transaction
ALTER TABLE users ADD COLUMN plan text DEFAULT 'free'; -- -> instant since PG11 (no table rewrite)
-- adding NOT NULL without a long lock
ALTER TABLE users ADD CONSTRAINT plan_nn CHECK (plan IS NOT NULL) NOT VALID; -- -> instant
ALTER TABLE users VALIDATE CONSTRAINT plan_nn; -- -> scans, but allows reads/writes
ALTER TABLE users ALTER COLUMN plan SET NOT NULL; -- -> uses the check, skips scan (PG12+)
-- same trick for foreign keys: ADD CONSTRAINT ... NOT VALID, then VALIDATEBackfill in batches → one UPDATE on 50M rows = one huge transaction: 50M new row versions, locks held for minutes, vacuum blocked, replicas lag. Small batches instead:
UPDATE users SET plan = 'free'
WHERE id IN (SELECT id FROM users WHERE plan IS NULL LIMIT 5000);
-- -> repeat from a script until it updates 0 rows, short sleep between batchesint → bigint on a big table without a long lock:
ALTER TABLE events ADD COLUMN id_new bigint;(instant)- Trigger copies
idintoid_newfor new/updated rows - Backfill old rows in batches
CREATE UNIQUE INDEX CONCURRENTLYonid_new- One short transaction: drop old PK, rename columns, add PK
USING INDEX, move the sequence
Every step except the last runs while the app keeps writing.
Rename/drop a column the app uses → expand and contract, each step is its own deploy:
flowchart LR
A[Add new column] --> B[App writes both] --> C[Backfill old rows in batches] --> D[App reads new] --> E[Stop writing old] --> F[Drop old column]
5. Functions, views & triggers
- View → saved query, no data stored.
- Materialized view → stores the result.
REFRESH MATERIALIZED VIEW CONCURRENTLY mv;(needs a unique index, doesn’t block reads).
Procedural languages
Write logic (loops, IF, variables) inside the DB.
- PL/pgSQL → default and most used. Loops,
IF, variables, exception handling. - PL/Python (
plpython3u) → use Python libraries inside the DB. Untrusted (u), only superuser can create functions.
CREATE FUNCTION calculate_discount(price NUMERIC, discount NUMERIC) RETURNS NUMERIC AS $$
BEGIN
RETURN price * (1 - discount);
END;
$$ LANGUAGE plpgsql;
CREATE FUNCTION python_greeting(name TEXT) RETURNS TEXT AS $$
return f"Hello, {name}!"
$$ LANGUAGE plpython3u;- Function vs procedure → function is called in
SELECTand can’tCOMMIT. Procedure isCALLed and can commit inside (batch jobs). - Volatility →
IMMUTABLE(same input = same output forever),STABLE(same within a query, e.g.now()),VOLATILE(default, e.g.random()). Planner uses this, and expression indexes needIMMUTABLE.
Triggers
CREATE FUNCTION set_updated_at() RETURNS trigger AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_users_updated
BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION set_updated_at();Gotcha → hidden logic nobody sees in app code, and slows bulk writes. Keep them for data integrity / audit, not business logic.
LISTEN/NOTIFY → trigger calls pg_notify('orders', id::text), app LISTEN orders and reacts. Not durable: if the listener is down the message is lost (same as Redis pub/sub in Redis).
6. Transactions, MVCC & locks
In nutshell → readers never block writers and writers never block readers. Every UPDATE writes a new row version and each transaction reads from a snapshot. Theory of ACID in ACID.
How it works
- Every row version (tuple) has hidden columns
xmin(txn that created it) andxmax(txn that deleted/updated it). - A snapshot = list of transactions that were committed when I started. It decides which versions I can see.
UPDATE= mark old version dead (xmax= my txn) + insert a new version.- Dead versions stay until vacuum cleans them → 3. Vacuum, bloat & XID wraparound
flowchart LR
subgraph Page0["Heap page 0 after UPDATE"]
T1["(0,1) bal=500<br/>xmin=750 xmax=751<br/>DEAD after 751 commits"]
T2["(0,2) bal=400<br/>xmin=751 xmax=0<br/>LIVE"]
end
T1 -- "t_ctid points to newer version" --> T2
S1["Snapshot started before 751 commits"] -. sees .-> T1
S2["Snapshot started after 751 commits"] -. sees .-> T2
CREATE TABLE acc (id int PRIMARY KEY, bal int);
INSERT INTO acc VALUES (1, 500);
SELECT xmin, xmax, ctid, * FROM acc; -- -> xmin=750 xmax=0 ctid=(0,1)
UPDATE acc SET bal = 400 WHERE id = 1;
SELECT xmin, xmax, ctid, * FROM acc; -- -> xmin=751 ctid=(0,2): a NEW tuple. (0,1) is now deadTwo sessions
-- session A
BEGIN;
UPDATE acc SET bal = 300 WHERE id = 1; -- -> not committed yet
-- session B
SELECT bal FROM acc WHERE id = 1; -- -> 400. sees old version, doesn't wait
UPDATE acc SET bal = 200 WHERE id = 1; -- -> WAITS: writers do block writers on the same row
-- session A
COMMIT; -- -> B continuessequenceDiagram
participant A as Session A
participant DB as acc row id=1
participant B as Session B
A->>DB: BEGIN, UPDATE bal=300
Note over DB: new version (300) not committed
B->>DB: SELECT bal
DB-->>B: 400 (old version, no wait)
B->>DB: UPDATE bal=200
Note over B,DB: blocked, row locked by A
A->>DB: COMMIT
DB-->>B: lock granted, B updates the 300 version
Isolation levels
| Level | Dirty read | Non-repeatable read | Phantom | Write skew |
|---|---|---|---|---|
| Read uncommitted | behaves as Read committed in PG | |||
| Read committed (default) | no | yes | yes | yes |
| Repeatable read | no | no | no (PG blocks it too) | yes |
| Serializable | no | no | no | no |
- Read committed → new snapshot per statement.
- Repeatable read → one snapshot per transaction. Updating a row someone else changed → error, retry.
- Serializable → acts as if txns ran one by one. Can fail with error
40001→ app must retry.
Lost update (classic bug) → app reads balance 500, subtracts 100 in code, writes 400. Two requests at once → one subtraction lost.
sequenceDiagram
participant R1 as Request 1
participant DB as bal = 500
participant R2 as Request 2
R1->>DB: SELECT bal
DB-->>R1: 500
R2->>DB: SELECT bal
DB-->>R2: 500
R1->>DB: UPDATE bal = 400 (500 - 100)
R2->>DB: UPDATE bal = 400 (500 - 100)
Note over DB: 400, but should be 300
Fixes:
- do it in SQL:
UPDATE acc SET bal = bal - 100 WHERE id = 1 - lock the row:
SELECT ... FOR UPDATEthen update - optimistic:
UPDATE ... WHERE id = 1 AND version = 7and check rows affected
Locks
- Row locks →
FOR UPDATE,FOR NO KEY UPDATE,FOR SHARE. Stored in the tuple itself (xmax), not in memory → millions of row locks are fine. - Table locks → from
ACCESS SHARE(any SELECT) toACCESS EXCLUSIVE(DROP, most ALTER TABLE) which blocks everything. - SKIP LOCKED → simple job queue, many workers never pick the same job:
SELECT id FROM jobs WHERE status = 'pending'
ORDER BY id LIMIT 1
FOR UPDATE SKIP LOCKED;- Advisory locks → app-level mutex:
SELECT pg_advisory_xact_lock(42);(released at commit). Good for “only one cron runs”. - Deadlock → T1 locks row 1 then 2, T2 locks row 2 then 1. PG detects after
deadlock_timeout(1s) and kills one. Fix: always lock in the same order (e.g. sort ids).
flowchart LR
T1((T1)) -- holds --> R1[row 1]
T2((T2)) -- holds --> R2[row 2]
T1 -. waits for .-> R2
T2 -. waits for .-> R1
Gotcha → a session idle in transaction holds its locks and its snapshot → blocks vacuum. Set idle_in_transaction_session_timeout.
-- who is blocked and by whom
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, query
FROM pg_stat_activity WHERE wait_event_type = 'Lock';7. Indexing
In nutshell → an index is a separate sorted structure that points to the row’s physical address (ctid) in the table. Faster reads, slower writes, more disk. B-Tree theory in B-Tree vs B+ Tree.
Postgres tables are a heap (rows in no order), not clustered like MySQL InnoDB → every index, even the primary key, is a “secondary” index pointing into the heap.
flowchart LR
subgraph IDX["B-tree index on email (sorted)"]
Root[root] --> L1["a@x.com -> (3,7)<br/>b@x.com -> (0,2)"]
Root --> L2["c@x.com -> (5,1)<br/>d@x.com -> (1,4)"]
end
subgraph HEAP["Heap (table file, no order)"]
P0["page 0"]
P1["page 1"]
P3["page 3"]
P5["page 5"]
end
L1 -- "ctid (0,2)" --> P0
L1 -- "ctid (3,7)" --> P3
L2 -- "ctid (1,4)" --> P1
L2 -- "ctid (5,1)" --> P5
Index Scan = walk the tree → get ctid → jump to that heap page. Many matches = many random page jumps → that’s why the planner sometimes prefers a Seq Scan.
| Type | Good for | Example |
|---|---|---|
| B-tree (default) | =, <, >, BETWEEN, ORDER BY, LIKE 'abc%' | CREATE INDEX ON orders (created_at) |
| Hash | only =, rarely better than B-tree | |
| GIN | many values in one row: jsonb, arrays, full-text, trigram | USING gin (payload) |
| GiST | ranges, geometry, overlap, nearest neighbour, exclusion | USING gist (during) |
| BRIN | huge append-only tables where value follows physical order (logs by time). Tiny index | USING brin (created_at) |
| HNSW (pgvector) | vector similarity | section 10 |
LIKE 'abc%' uses B-tree only with C collation or text_pattern_ops.
Composite, partial, expression, covering
-- composite: leftmost rule
CREATE INDEX ON orders (user_id, created_at);
-- helps: WHERE user_id = 1
-- helps: WHERE user_id = 1 AND created_at > now() - interval '7 days'
-- helps: WHERE user_id = 1 ORDER BY created_at DESC
-- mostly not: WHERE created_at > ... (PG18 skip scan can sometimes)
-- rule: equality columns first, then range / sort column
-- partial: index only the rows you query
CREATE INDEX ON orders (created_at) WHERE status = 'pending';
-- expression: query must use the same expression
CREATE INDEX ON users (lower(email));
SELECT * FROM users WHERE lower(email) = 'a@x.com';
-- covering: answer from index alone (Index Only Scan)
CREATE INDEX ON orders (user_id) INCLUDE (amount);When the index is NOT used
- function on the column without an expression index (
WHERE lower(email) = ...) - type mismatch / implicit cast (comparing
bigintcolumn with text param) - leading wildcard
LIKE '%abc'→ usepg_trgmGIN index (section 10) - query returns a big part of the table → seq scan is actually cheaper, planner is right
- stale statistics → run
ANALYZE orders
Maintenance
- Every index slows
INSERT/UPDATE: anUPDATEwrites a new row version at a newctid(section 6), so normally every index on the table gets a new entry pointing to it, even indexes on columns we didn’t change. - HOT update (Heap Only Tuple) is the exception: if none of the changed columns are indexed and the new version fits in the same page, Postgres links old → new inside the page and skips all index writes. One extra index on a frequently updated column (
updated_at,view_count) turns every update back into “write to all indexes”. - Drop unused ones:
SELECT relname, indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid))
FROM pg_stat_user_indexes ORDER BY idx_scan; -- -> idx_scan = 0 means never used- Bloated index →
REINDEX INDEX CONCURRENTLY idx_name;
8. Query planning & performance
In nutshell → the planner estimates the cost of possible plans using table statistics and picks the cheapest. Bad estimates = bad plans.
flowchart LR
AN["ANALYZE / autovacuum"] --> ST[("pg_stats: MCVs, histogram, n_distinct")]
Q[Query] --> PL[Planner]
ST --> PL
CFG["Cost settings: random_page_cost, work_mem"] --> PL
PL --> C1["Plan A: Seq Scan, cost 1800"]
PL --> C2["Plan B: Index Scan, cost 12"]
C2 -->|cheapest wins| EX[Executor]
EXPLAIN→ shows the plan, doesn’t run.EXPLAIN (ANALYZE, BUFFERS)→ runs it and shows real time and rows. ForUPDATE/DELETEwrap inBEGIN; ... ROLLBACK;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE user_id = 42 ORDER BY created_at DESC LIMIT 10;
Limit (cost=0.43..12.10 rows=10 width=48) (actual time=0.031..0.045 rows=10 loops=1)
-> Index Scan Backward using orders_user_id_created_at_idx on orders
(cost=0.43..560.12 rows=480 width=48) (actual time=0.030..0.042 rows=10 loops=1)
Index Cond: (user_id = 42)
Buffers: shared hit=13
Planning Time: 0.120 ms
Execution Time: 0.070 ms
How to read it
- Read inside out, the most indented node runs first.
cost=startup..total→ planner’s guess in arbitrary units, only useful to compare plans.rows=480(estimate) vsactual rows→ big gap = stale/missing stats, the most common root cause.loops→ node ran N times, multiply time by loops.Buffers: shared hit= pages from cache,read= from disk.
| Scan | When |
|---|---|
| Seq Scan | reads whole table. Fine for small tables or when most rows match |
| Index Scan | few rows, walks index then fetches each row from heap |
| Index Only Scan | all needed columns in the index, skips heap. Index has no xmin/xmax, so it can’t tell if a row is visible to us. Postgres checks the visibility map (1 bit per page = “every row here is visible to everyone”, set by vacuum). Bit set → skip the heap. Not set → fetch the row anyway. Heap Fetches: 0 in EXPLAIN = working well |
| Bitmap Heap Scan | medium number of rows, collects ctids first then reads pages in order |
| Join | When |
|---|---|
| Nested Loop | small outer side, indexed inner side |
| Hash Join | big, unsorted, equality join. Builds hash table of smaller side |
| Merge Join | both sides already sorted on the join key |
Statistics
ANALYZEsamples the table and stores stats inpg_stats(most common values, histogram, distinct count). Autovacuum runs it automatically.- Skewed column →
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000; - Correlated columns (city + zip) → planner assumes independent and under-estimates →
CREATE STATISTICS ON city, zip FROM addresses;
Tuning checklist
- Find the slow queries →
pg_stat_statements(8. Monitoring & incident response) EXPLAIN (ANALYZE, BUFFERS)it- Estimate vs actual way off? →
ANALYZE, extended stats - Seq scan on a big table returning few rows? → add the right index (section 7)
Sort Method: external merge Disk→ sort spilled to disk → raisework_memfor that query- Same small query run 100s of times → N+1 from the app (section 9)
- Deep pagination
OFFSET 100000reads and throws away 100k rows → keyset pagination:
SELECT * FROM orders
WHERE (created_at, id) < ($last_created_at, $last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;9. Application development
Connection pooling
Every connection is a process (section 1) → opening one per request is slow and 1000 connections kill the DB.
flowchart LR
subgraph Apps["20 app pods"]
A1["pod pool (10 conns)"]
A2["pod pool (10 conns)"]
A3["... 200 client conns total"]
end
A1 --> PGB
A2 --> PGB
A3 --> PGB
PGB["PgBouncer, transaction mode"] -- "20 server conns" --> PG[(PostgreSQL)]
200 app connections share 20 real Postgres processes, because a server connection is only taken while a transaction is running.
- App-side pool (node-postgres pool, HikariCP, SQLAlchemy pool) + PgBouncer in between when many app instances.
- More connections ≠ faster. A small pool (around cores × 2–4) usually beats a big one.
- PgBouncer transaction mode gotcha → the server connection changes between transactions, so session state breaks:
SET(useSET LOCAL), session advisory locks,LISTEN. Prepared statements need PgBouncer 1.21+ (max_prepared_statements).
Parameter placeholders
Never build SQL by string concat with user input → SQL injection. With placeholders the driver sends the query and the values separately, so input is always data, never code.
- Postgres native:
$1, $2(node-postgres uses this) - psycopg: positional
%s, named%(name)s - Cast when needed:
WHERE id = %(id)s::integer - Lists / dicts map to arrays / jsonb
cur.execute(
"INSERT INTO documents (title, content) VALUES (%(title)s, %(content)s)",
{"title": "My Title", "content": "Some content here."},
)ORMs
- N+1 → load 100 users, then 1 query per user for orders = 101 queries. Use the ORM’s eager loading (
include,joinedload) or one JOIN. - Turn on SQL logging in dev and read what the ORM generates.
- Raw SQL for reports, bulk updates, window functions. Notes on Prisma in Prisma.
Transactions from the app
- Keep them short. No HTTP calls inside a transaction (payment API slow → locks held → pile up).
- Retry on
40001(serialization failure) and40P01(deadlock). - Set
statement_timeoutper app role so one bad query can’t run forever:ALTER ROLE api SET statement_timeout = '5s';
Bulk load & export
COPYis the fastest way in/out.\copyin psql does it from the client machine.
\copy orders FROM 'orders.csv' WITH (FORMAT csv, HEADER)
\copy (SELECT * FROM orders WHERE status = 'paid') TO 'paid.csv' WITH (FORMAT csv, HEADER)- Inserting from app → multi-row
VALUES (...), (...), ...in batches of ~1000, not one insert per row.
10. Search & extensions
Postgres alone can be a decent search engine. Combine:
- Full-text search with
tsvector - Fuzzy matching with
pg_trgm - Semantic search with
pgvector - Bonus: BM25
Full-text search
to_tsvector splits text into words, removes stop words and stems them (running → run).
ALTER TABLE docs ADD COLUMN tsv tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(title, '') || ' ' || coalesce(content, ''))) STORED;
CREATE INDEX ON docs USING gin (tsv);
SELECT title, ts_rank(tsv, q) AS rank
FROM docs, websearch_to_tsquery('english', 'postgres index -mysql') q -- -> google-like syntax
WHERE tsv @@ q
ORDER BY rank DESC LIMIT 10;coalesce matters → 'text' || NULL is NULL, the whole document becomes unsearchable.
Fuzzy with pg_trgm
Splits text into 3-letter chunks → handles typos and makes LIKE '%abc%' use an index.
CREATE EXTENSION pg_trgm;
CREATE INDEX ON users USING gin (name gin_trgm_ops);
SELECT name, similarity(name, 'boopthi') FROM users WHERE name % 'boopthi' ORDER BY 2 DESC;Semantic with pgvector
CREATE EXTENSION vector;
CREATE TABLE chunks (id bigint, content text, embedding vector(1536));
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
SELECT content FROM chunks ORDER BY embedding <=> $1 LIMIT 5; -- -> <=> cosine distanceBM25
ts_rank is not BM25 (no proper term rarity weighting). For real BM25 use an extension like ParadeDB pg_search. Hybrid search = run keyword + vector search and merge the results with Reciprocal Rank Fusion.
flowchart LR
Q[User query] --> FT["Full-text / BM25 (exact words)"]
Q --> EMB[Embed query] --> VS["pgvector (meaning)"]
Q --> TG["pg_trgm (typos)"]
FT --> RRF["Merge: score = sum of 1 / (60 + rank)"]
VS --> RRF
TG --> RRF
RRF --> TOP[Top 10 results]
Extensions
PostgreSQL has a rich ecosystem of extensions that enhance its functionality.
SELECT * FROM pg_available_extensions;
CREATE EXTENSION pg_stat_statements; -- -> also needs shared_preload_libraries + restart| Extension | What |
|---|---|
pg_stat_statements | execution stats of every query. Must have |
pg_trgm | fuzzy search, fast LIKE '%x%' |
pgvector | vector embeddings & similarity search |
| PostGIS | geo types, “nearby within 5km” queries |
| TimescaleDB | time-series: auto partitioned hypertables, compression |
pg_cron | cron jobs inside the DB |
pg_partman | automatic partition creation/retention |
postgres_fdw | query another Postgres as if local tables |
Resources
- https://pgrun.dev/postgres-internals
- https://www.postgresql.org/docs/current/
- https://www.interdb.jp/pg/ (The Internals of PostgreSQL)
- https://explain.dalibo.com (paste EXPLAIN output, get a visual plan)
- https://use-the-index-luke.com