skip to content

sql, all the way down

a free, visual book about SQL and the database underneath it. from your first SELECT to the bytes on disk, on a real postgres running in your browser.

or scroll, and follow one query all the way down.

a b-tree drawn as a field of dots: a root page, three internal pages and six leaf pages joined by links, with a heap page of rows underneath. the path of the last lookup, id 42, runs in amber from the root to one leaf entry, and a pointer goes from that entry to one green row on the heap page. a few rows on the heap page are hollow red rings: dead tuples.

select * from t where id = 42;

heap: tid (0,13), the row comes back

one query, all the way down

what actually happens when you run SELECT name FROM customers WHERE id = 42. every artefact below is real output from postgres 18.6, made by the command printed above it.

your query

depth 00 of 10

one line. you say what you want, never how to get it. that's the deal SQL makes, and everything below is postgres keeping its side of it.

read: your first query
psql · db=shop
SELECT name FROM customers WHERE id = 42;
     name     
--------------
 Ada Lovelace 
(1 row)

the parser

depth 01 of 10

characters become tokens, tokens become a tree. the parser knows grammar and nothing else: it has no idea whether customers exists. misspell FROM and watch where it actually complains.

read: the life of a query
tokens, then the grammar
SELECTnameFROMcustomersWHEREid=42;
  word  |  catdesc   
--------+------------
 from   | reserved   
 name   | unreserved 
 select | reserved   
 where  | reserved   
(4 rows)
=> SELECT name FORM customers WHERE id = 42;
ERROR:  syntax error at or near "customers"
LINE 1: SELECT name FORM customers WHERE id = 42;
                         ^

name is unreserved, so it can be a column. FORM became an alias for it (AS is optional), so the parser only got lost one word later. the chips are this site's tokenizer; the rest is postgres.

the analyzer

depth 02 of 10

now names become numbers. customers is relation 16385, name is column 2, of type 25 (text). this is the step that says relation "custmers" does not exist.

read: the system catalog
SET debug_print_parse = on
LOG:  parse tree:
:relid 16385
:eref {ALIAS :aliasname customers :colnames ("id" "name" "email" "…
{VAR :varno 1 :varattno 2 :vartype 25 :vartypmod -1 :varcollid 100…
:resname name
… the whole tree is 2,980 characters
the catalog says the same:
  oid  | attnum | atttypid 
-------+--------+----------
 16385 |      2 |       25 
(1 row)

the planner

depth 03 of 10

there are many ways to fetch one row. the planner prices each in made-up units and keeps the cheapest: walk the primary key, read one heap page. reading every row would cost about 6x more.

read: the cost model
EXPLAIN
Index Scan using customers_pkey on customers (cost=0.28..8.29 rows=1 width=12)
Index Cond: (id = 42)
SET enable_indexscan = off; SET enable_bitmapscan = off;
Seq Scan on customers (cost=0.00..49.00 rows=1 width=12)
Filter: (id = 42)
index scan8.29
seq scan49.00

the executor

depth 04 of 10

the plan is a tree of iterators. the top asks for a row, the index scan asks the index, the index hands back an address. one next() returns Ada, the next one returns nothing, and the query is over.

read: the executor and the iterator model
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF)
Index Scan using customers_pkey on customers (cost=0.28..8.29 rows=1 width=12) (actual rows=1.00 loops=1)
Index Cond: (id = 42)
Index Searches: 1
Buffers: shared hit=3
→ next()  →  (Ada Lovelace)
  next()  →  end of scan

the index

depth 05 of 10

the index is a b+tree on id. the root says which leaf to visit, and the leaf holds the key 42 next to an address: (0,42), page 0, slot 42 of the table. that address is a ctid.

read: a real b-tree, page by page
pageinspect · bt_metap, bt_page_items
root page 3, level 1
off  child  keys from
  1  → 1    -∞
  2  → 2    367
  3  → 4    733
  4  → 5    1099
  5  → 6    1465
  6  → 7    1831
leaf page 1, the entry for 42:
off 43 ctid (0,42) data 2a 00 00 00 00 00 00 00

42 sorts before every separator, so the walk takes the first child. 2a is 42 in hex, stored little-endian.

the buffer pool

depth 06 of 10

postgres never reads straight from disk into your query. every page goes through a shared cache first. cold, the query read 3 pages. run it again and it hit the same 3. same query, no I/O.

read: the buffer pool
pg_buffercache (evicting is new in postgres 18)
pg_buffercache_evict_relation('customers') evicted 1
pg_buffercache_evict_relation('customers_pkey') evicted 3
cold   Buffers: shared read=3
again  Buffers: shared hit=3
      rel       | block | usage | dirty 
----------------+-------+-------+-------
 customers      |     0 |     2 | f     
 customers_pkey |     1 |     2 | f     
 customers_pkey |     3 |     2 | f     
(3 rows)

the page

depth 07 of 10

every table is a stack of 8 KB pages. slot 42 is a 4-byte line pointer near the top of page 0, pointing at its tuple further down: a header that says who wrote it, then Ada.

read: the 8 KB page
pageinspect · page_header, heap_page_items
lp 42  lp_off 4648  lp_len 80  t_hoff 24
t_xmin 752  t_xmax 752  t_ctid (0,42)
HASVARWIDTHXMAX_KEYSHR_LOCKXMAX_LOCK_ONLYXMIN_COMMITTEDXMAX_INVALID

t_xmax 752 isn't a delete. XMAX_LOCK_ONLY: it's a key-share lock, left when the load's foreign key checks looked Ada up. XMAX_INVALID: nobody deleted her.

the bytes

depth 08 of 10

and at the bottom, a file: base/5/16385. page 0 is its first 8,192 bytes. the first eight are the LSN of the last WAL record that touched it, and inside Ada's tuple sits 2a 00 00 00, the 42 from your WHERE clause.

read: the files behind a table
get_raw_page('customers', 0) · base/5/16385
00 00 00 00 28 5b dd 01pd_lsn0/1DD5B28
5f 6fchecksum0x6f5f
04 00flags0x0004
80 01lower384
a0 01upper416
00 20special8192
04 20size, version8192, 4
00 00 00 00prune_xid0
the tuple: 80 bytes at byte 4648
000  f0 02 00 00 f0 02 00 00
008  48 00 00 00 00 00 00 00
016  2a 00 06 00 92 09 18 00
024  2a 00 00 00 1b 41 64 61
032  20 4c 6f 76 65 6c 61 63
040  65 21 61 64 61 40 65 78
048  61 6d 70 6c 65 2e 63 6f
056  6d 0f 4c 6f 6e 64 6f 6e
064  07 47 42 00 00 00 00 00
072  00 51 bc 96 a7 b1 02 00

the first 24 bytes are the tuple header (xmin, xmax, ctid, flags), then 2a 00 00 00 is id 42 and Ada Lovelace follows. this is the page in memory, which is the page on disk after a checkpoint, except the checksum, which is stamped on the way out.

and the WAL

depth 09 of 10

change the row and the first thing written isn't the table, it's a log record. postgres appends to the write-ahead log, flushes it at COMMIT, and writes the page later. the log is the truth. the table catches up.

read: WAL records and LSNs
pg_walinspect · pg_get_wal_records_info
=> UPDATE customers SET city = 'Paris' WHERE id = 42;
UPDATE 1
start_lsn rmgr        record_type length   fpi
0/1F785D0 Heap        LOCK          8219  8160
0/1F7A608 Heap        UPDATE        8586  8500
0/1F7C7B0 Btree       INSERT_LEAF   7453  7400
0/1F7E4E8 Btree       INSERT_LEAF   5581  5528
0/1F7FAB8 Transaction COMMIT          34     0

the new version didn't fit on page 0, so it went to page 23: the old tuple is locked, the UPDATE is logged, each of the two indexes gets an entry, then the COMMIT. each page's first change since the last checkpoint carries a full page image, so one changed row logged 29 KB.

and the old version

depth 10 of 10

the UPDATE didn't change Ada's row. it wrote a new version and stamped the old one with its transaction id in xmax. anyone already reading still sees the old one. once nobody can, VACUUM frees the slot.

read: an UPDATE is an INSERT
pageinspect · heap_page_items, before and after VACUUM
after the UPDATE, slot 42 on page 0:
lp_flags 1 (normal) t_xmax 801 t_ctid → (23,3)
=> VACUUM customers;
lp_flags 0 (unused) t_xmax null t_ctid null

the old version's t_ctid points at the new one, on page 23. once xmax 801 committed and no snapshot could still want the old one, it was dead. VACUUM removed it and the index entries pointing at it, and slot 42 is free again.

depth 0, your query
psql · db=shop
SELECT name FROM customers WHERE id = 42;
     name     
--------------
 Ada Lovelace 
(1 row)

the whole book

18 parts, 198 chapters. read it in order, or jump to whatever you're stuck on. your progress stays in your browser.

  1. start here01, 7 ch

    what a database actually is, the real postgres running in this page, and your first query.

  2. one table02, 12 ch

    SELECT, WHERE, NULL, ORDER BY and GROUP BY. everything you can ask of a single table.

  3. joins and subqueries03, 11 ch

    putting tables back together. every join, semi and anti joins, subqueries, set operations and CTEs.

  4. windows, grouping and recursion04, 11 ch

    the queries that make spreadsheets jealous. window functions, grouping sets and recursive CTEs.

  5. changing data05, 10 ch

    INSERT, UPDATE, DELETE, upserts, MERGE, bulk loads, and code that runs inside the database.

  6. types and values06, 11 ch

    numbers, text, time, json, arrays and ranges. picking the type is half the schema.

  7. schema design07, 13 ch

    keys, constraints, normal forms, and the patterns that keep data honest as it grows.

  8. indexes, from the outside08, 12 ch

    what an index is for, which queries it can help, and what it costs on every write.

  9. how a query runs09, 13 ch

    parse, plan, execute. EXPLAIN, scans, joins, sorts, and the iterator that pulls one row at a time.

  10. the optimizer10, 10 ch

    how postgres guesses row counts, prices every plan and picks the cheapest. and how it gets that wrong.

  11. transactions and isolation11, 11 ch

    ACID, the anomalies, the isolation levels, and what postgres really gives you at each one.

  12. pages and the buffer pool12, 12 ch

    where rows physically live. files, 8 KB pages, tuple headers, TOAST, and the cache in front of the disk.

  13. inside indexes13, 12 ch

    b+trees page by page, splits under concurrency, and how hash, GIN, GiST, BRIN and LSM trees are built.

  14. MVCC and vacuum14, 12 ch

    why an UPDATE writes a new row, who can see which version, and the vacuum that cleans up after everyone.

  15. locks and concurrency control15, 10 ch

    serializability theory, two-phase locking, postgres's lock manager, and the SSI that catches write skew.

  16. WAL and recovery16, 11 ch

    write-ahead logging, LSNs, checkpoints, crash recovery, backups and replication.

  17. scale and distribution17, 10 ch

    pools, partitions, replicas, shards, and what changes when the data no longer fits on one machine.

  18. deep dives and interviews18, 10 ch

    one row traced end to end, other engines compared, the interview questions, and a toy database you build yourself.

the house rules

what every page here promises.

queries
real. every snippet runs on postgres 18.6, right here in your browser.
figures
they move. step them, slide them, break them.
internals
every page, tuple and WAL record you see was captured from a real server.
depth
from your first SELECT to the bytes on disk, in one voice.
price
free. MIT licensed. no account, no ads, no tracking.