A query is a pipeline over tables (pair rows, keep the true ones, group, compute, order), and most SQL bugs are queries that run and return plausible wrong numbers; a schema is the rules every write must pass, so put each fact in one place, every rule in a constraint, and change the schema only in small, backward-compatible steps.
Fig. 1 runs one real query over the page's data, then one write:
SELECT u.plan, COUNT(*) AS chats FROM users u JOIN chats c ON c.user_id = u.id WHERE c.model = 'mini' GROUP BY u.plan ORDER BY chats DESC;
c.user_id = u.id is true for exactly one user per chat: 200 dots, a staircase because both edges are sorted by user. The six users with no chat have no dot, so an inner join drops them (section 2).c.model = 'mini' is true pass (section 1): 90 of the 200; the other 110 vanish.chats.user_id looks the user up on every insert: a chat for user 7 goes in; one for user 999 is refused, violates foreign key constraint "chats_user_id_fkey" (section 10).You need: the first six clauses (SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT) on this data, taught in the root page (Reading section 2 and its SQL playground). How the database runs a query is Query planning and performance; transactions and isolation are Transactions and concurrency; how rows and indexes sit on disk is Storage engines and indexes; analytics engines are Analytics: columnar engines, DuckDB and the lakehouse. This page is what the query means and what the schema promises.
WITH name AS (...); recursive when it refers to itself.Every grey box with a Run button is a real database: SQLite (the most widely deployed database engine, by its authors' count) compiled to WebAssembly inside this page, the root playground's engine, with the same query's result on a real PostgreSQL server (Postgres: the free relational database the root recommends as the default) recorded offline. Where the two agree the Postgres result is folded away; where they disagree both show, and those differences are where real teams get bitten. Numbers marked measured were measured for this page on a laptop (Apple M1 Pro, PostgreSQL 16.2 from the pgserver wheel); illustrative marks anything made up to show a shape. Two tabs sit beside this one: Exercises lab (28 graded exercises on this data, checked by the page's own database) and ALTER TABLE, measured (21 schema changes with the lock each took on a 2,000,000-row table).
The root's chat data: 50 users, 200 chats, 2,000 messages, one credits balance per user. PK is a primary key (a column whose value names exactly one row), FK a foreign key (a column holding another table's primary key). This page adds one column, messages.parent_id (the previous message in its chat; empty for the first), the arrow back into messages that makes a thread a tree.
A SELECT is defined as a pipeline of steps, each producing a table for the next, in an order that is not the order you write it (the PostgreSQL SELECT reference lists it; every SQL database follows the same logical order). The order explains most "why is this an error" moments.
Read top to bottom: the evaluation order. A dot means the step can use it. Hence WHERE cannot use a SELECT alias (SELECT has not run) but ORDER BY can; WHERE cannot use an aggregate such as COUNT(*) (filter groups with HAVING); WHERE cannot use a window function (compute it in a subquery, filter outside); and LIMIT without ORDER BY returns whichever rows the engine found first, an order that can change when the data or the plan changes. The root animates the same pipeline on nine rows.
SQLite accepts the alias, Postgres reports column "doubled" does not exist; write WHERE tokens * 2 > 1780 and both agree. Test against the database you run in production: SQLite's dialect is more permissive (aliases in WHERE, loose GROUP BY, foreign keys off by default, loose typing); run Postgres in a container or with pgserver in CI.
NULL means "unknown", not zero or empty, and SQL computes with three truth values. Any comparison with NULL (= NULL, <> 'US' when the country is NULL) is unknown, and WHERE, ON and HAVING keep only rows where the condition is true, so unknown rows silently vanish. The tables below are the whole of the logic; every NULL trap on this page (the LEFT JOIN filtered in WHERE, NOT IN with a NULL, COUNT(column) skipping NULLs) is one of their cells.
| AND | T | F | U |
|---|---|---|---|
| T | T | F | U |
| F | F | F | F |
| U | U | F | U |
| OR | T | F | U |
|---|---|---|---|
| T | T | T | T |
| F | T | F | U |
| U | T | U | U |
| x | NOT x | x = NULL | x IS NULL |
|---|---|---|---|
| T | F | U | F |
| F | T | U | F |
| U | U | U | T |
T true, F false, U unknown. IS NULL, IS DISTINCT FROM and COALESCE are the operators that turn unknown into a definite answer. Aggregates skip NULLs: COUNT(*) counts rows, COUNT(column) counts non-NULL values (the root's playground has a NULL lesson, including where NULLs sort). Set operations and GROUP BY are the exceptions that treat two NULLs as equal (section 6).
A join pairs every row of a left table with every row of a right table and keeps the pairs for which the ON condition is true. Read it that way and every kind of join follows. It is not a set intersection, which is why Venn-diagram pictures mislead: a left row appears once per matching right row, so zero, one or many times (Lukas Eder, "Say NO to Venn diagrams when explaining JOINs", jOOQ blog, 2016). So draw the pairs: in Fig. 2 every cell is one pair of a user and a market, raised where ON m.code = u.country is true, flat where false, U where it is unknown because a NULL is involved. Predict each join's rows before its step.
EXISTS or IN (subquery) keeps a user once if any cell in the row is true, however many match: 3 rows. Writing it as a plain JOIN repeats rows, the classic source of "why do I have duplicates?" and of a DISTINCT added to hide it: 42 joined rows against 27 users in the box below.NULL NOT IN (...) is unknown, not true. 1 row.A self join joins a table to itself under two names; with parent_id, each assistant reply sits next to the prompt it answers.
A LEFT JOIN filtered in WHERE becomes an inner join. A condition on the right table in WHERE throws away the NULL rows LEFT JOIN kept, because NULL = 'reasoning' is unknown, not true: 27 users instead of 50. Conditions that should only limit what is matched belong in ON.
NOT IN with a NULL returns nothing. x NOT IN (a, b, NULL) means x <> a AND x <> b AND x <> NULL; the last term is unknown for every x, so by the AND table the whole condition is never true (the last step of Fig. 2). Two of the five team-plan users have no country, so the subquery holds a NULL: 0 rows against NOT EXISTS's 31. NOT EXISTS asks a different question ("is there a matching row?") and is not affected. The Postgres project's advice is blunt, "Don't use NOT IN" (PostgreSQL wiki), and it also tends to plan badly on large subqueries. Use NOT EXISTS.
Fan-out doubles your totals. Join a parent to a child and a grandchild (or to two child tables) and aggregate, and each parent and child row is repeated once per grandchild row before the aggregate runs. Nothing errors. The rule: aggregate each child table on its own, then join the results (CTEs make this readable, section 5). COUNT(DISTINCT c.id) fixes a count but not a sum.
GROUP BY collapses all rows sharing the grouping values into one row, and aggregate functions (COUNT, SUM, AVG, MIN, MAX) summarise each group. Every column in the SELECT list must then be grouped or aggregated; SQLite's leniency here (it picks an arbitrary row) is a lesson in the root's playground. A window function (section 4) computes the same aggregate but keeps every row. Same 16 rows, both ways, at one scale, so a stack is literally its sum:
PARTITION BY role splits a window the same way).SELECT role, COUNT(*), SUM(tokens) FROM messages WHERE chat_id = 11 GROUP BY role: user 8 rows and 477 tokens, assistant 8 rows and 3,826. 16 rows in, 2 rows out; the ids are gone, so a column such as id can no longer be selected unless it is grouped or aggregated.SUM(tokens) OVER (PARTITION BY role) writes its partition's total on each row: 477 on every user row, 3,826 on every assistant row. 16 rows in, 16 rows out.OVER (PARTITION BY role ORDER BY id) sums from the partition's first row to the current one: the user rows read 103, 204, 223 ... 477. Which rows the sum sees is the frame, section 4.Several counts in one pass. "Per model: messages, replies, reply tokens, distinct users" is conditional aggregation. The standard spelling is FILTER (WHERE ...), supported by Postgres and SQLite (modern-sql.com's support table); without it, write SUM(CASE WHEN ... THEN 1 ELSE 0 END). One scan replaces four queries:
The NULL cells of aggregation: COUNT(column) skips NULLs, so after a LEFT JOIN count the right table's key, not *, or every empty group counts as 1; SUM over zero rows is NULL, not 0 (wrap it in COALESCE(SUM(x), 0)); and an average of averages is wrong when groups differ in size (average the raw rows, or weight by count).
GROUP BY ROLLUP (plan, model) returns the per-plan-and-model rows, a subtotal row per plan (model shown as NULL) and a grand total (both NULL). CUBE and GROUPING SETS generalise it. SQLite has none of them, so this box is Postgres only. AVG of an integer column is a numeric with many digits in Postgres and a float in SQLite: round explicitly when you compare.
Many questions need every row and something about its neighbours: rank each user by tokens, the time since the previous message, a running total, the latest message per chat (before window functions, slow self joins or correlated subqueries). A window function's OVER (...) has three parts: PARTITION BY splits rows into independent groups (all rows if absent); ORDER BY orders rows inside each partition (ranking and LAG/LEAD need it); the frame says which rows around the current one an aggregate sees (ROWS BETWEEN 2 PRECEDING AND CURRENT ROW: this row and the two before). With an ORDER BY and no frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the start of the partition to the current row and every row tied with it (SQLite window functions; Postgres documents the same default).
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING: every row sees the chat's last message, 338 tokens.Two frame traps. LAST_VALUE with the default frame returns the current row's value, because the frame ends at the current row; ask for the whole partition. And the default frame is RANGE, so rows tied on the ORDER BY value enter together: two chats opened on the same day get the same running count. Say ROWS when you mean rows.
Rankings. ROW_NUMBER() numbers 1, 2, 3 even through ties (add a tie-breaker to its ORDER BY, or two runs can number tied rows differently); RANK() gives ties one number and leaves a gap (1, 1, 3); DENSE_RANK() leaves none (1, 1, 2). Top N per group, the most common production use: number the rows per partition in a subquery and keep rn <= N outside (a window result cannot be filtered in the same SELECT's WHERE, section 1). Postgres also has DISTINCT ON (user_id) ... ORDER BY user_id, ... for N = 1.
LAG(x) and LEAD(x) read a column from the row before or after. Time arithmetic is a dialect difference: Postgres subtracts timestamps into an interval; SQLite has no time type, so this box uses julianday there.
A common table expression, WITH name AS (SELECT ...), names a step of a query so later steps use it like a table (the fan-out fix in section 2 used two). It usually costs nothing: since PostgreSQL 12, a CTE that is referenced once, is not recursive and has no side effects is inlined into the main query and optimised with it; MATERIALIZED forces it to be computed once on its own, NOT MATERIALIZED forces inlining (PostgreSQL 12 release notes; WITH queries). Advice that "CTEs are an optimisation fence" describes Postgres 11 and earlier.
Recursion. WITH RECURSIVE is an anchor query, UNION ALL, and a step that joins the CTE's previous rows to find the next ones, repeated until a step adds no rows. It is how SQL walks a tree or graph of unknown depth: a reply thread, an org chart, a bill of materials, a category tree.
m.id = up.parent_id with 1682 as the only row finds its parent, 1681: one row, which replaces the working table. Earlier rows are never joined again.parent_id is NULL.m.id = NULL, never true (section 1): 16 rows in all. A cycle in parent_id would never reach this step, hence the depth limit or CYCLE clause below.A second use: generating rows no table holds, such as every day in a range, so days with no messages show as zero instead of vanishing from a chart (Postgres has generate_series; in SQLite a recursive CTE does it).
WHERE depth < 100) or, in Postgres 14 and later, the CYCLE clause. Trees read far more than written are often stored differently (section 8); traversals many hops deep across large graphs are the graph section of NoSQL in practice.Upsert: insert, or update if the key exists. Count each user's tokens per day. Code that reads the row, then inserts it if missing or updates it if present, races (a race condition: two operations interleaving so that the result depends on timing): two requests at once both read "missing" and both insert, so one fails on the primary key or, without a key, you get two rows. Let the database do both in one atomic statement: INSERT ... ON CONFLICT (key) DO UPDATE SET ..., where excluded names the row you tried to insert. It needs a UNIQUE constraint or primary key to detect the conflict. Postgres has had it since 9.5; SQLite copied the syntax in 3.24.0, 2018-06-04; MySQL spells it INSERT ... ON DUPLICATE KEY UPDATE. (Races in general, and isolation levels, are Transactions and concurrency.)
Idempotency. ON CONFLICT DO NOTHING plus RETURNING (which returns the inserted rows) makes a handler idempotent: safe to run twice with the same input, as a retried request or a webhook delivered twice will be. Building a backend API builds idempotency keys on exactly this.
MERGE (SQL standard; Postgres since version 15) states several cases in one statement: update when matched, insert when not, optionally delete; it reads well for syncing a table from a batch. But unlike ON CONFLICT, a Postgres MERGE with both INSERT and UPDATE branches "does not guarantee that either INSERT or UPDATE will occur" when another transaction is changing the same rows, so two concurrent MERGEs inserting the same new key can fail with a unique violation; the MERGE page points to INSERT ... ON CONFLICT for that case. MERGE for batch syncs, ON CONFLICT for concurrent single-row upserts.
Set operations combine two queries with the same columns. UNION stacks them and removes duplicates; UNION ALL keeps everything and is cheaper (no de-duplication step), so use it unless duplicates are genuinely wrong. INTERSECT keeps rows in both; EXCEPT rows in the first but not the second. All compare whole rows and, unlike =, treat two NULLs as equal. Postgres requires an alias on a subquery in FROM; SQLite does not.
Start from the nouns the product must remember, each with its own identity and lifecycle (a user, a chat, a message): each becomes a table, an entity, and its facts become columns, attributes. The verbs between them become relationships, and the kind decides where the key goes (all three are in the hero figure and the shapes of section 8):
A user has many chats; a chat has one user. The foreign key goes on the "many" side: chats.user_id. Most relationships.
Shared chats: a chat has many members, a user many shared chats. Neither table can hold the other's key, so a join table holds pairs, chat_members(chat_id, user_id, role) with the pair as its primary key, and is the natural place for facts about the membership itself (the role, when it started).
A user has one credits balance: credits.user_id is both primary key and foreign key. Split one-to-one only for a reason: a different write rate (a balance changes on every message, a profile rarely), optional data, or tighter access control.
A natural key is a real-world value that already identifies the row (an email address); a surrogate key is an id the database invents, with no meaning. Natural keys age badly: people change emails, case and whitespace make two spellings of one address, and a key copied into every foreign key must change everywhere when it changes. The production default: a surrogate primary key, plus a UNIQUE constraint on the natural key so duplicates are still refused. Join tables are the exception: the pair is the right primary key.
bigint GENERATED ALWAYS AS IDENTITY, the SQL-standard spelling Postgres has supported since version 10; the older serial is on the wiki's Don't Do This list): 8 bytes, sequential, compact. Use bigint, not integer: a 4-byte integer runs out at 2,147,483,647, and changing a key's type later rewrites the table and every index (ALTER TABLE, measured).uuidv7(); on 16 and 17 generate it in the application or with a small function (the measurement below used one).Why order matters is a B-tree mechanism: sequential keys append to the last leaf page, random keys split pages all over the index, leave them about 69% full and write more whole pages to the WAL (the write-ahead log, the record of every change written before the data, which replicas and backups also consume). Storage engines and indexes owns it: section 5 draws and measures it, and its B-tree and LSM lab lets you insert ascending against random keys. What it means for choosing a key, measured here:
PostgreSQL 16.2 on a laptop, default settings (128 MB of shared buffers). Keys generated first into a temporary table (generation timed apart: gen_random_uuid took 12.9 s per 1M here, more than the insert), then inserted in generation order with one INSERT ... SELECT into a table of the key plus two integers. 1M figures are medians of 3 runs, 10M single runs.
A UUID is twice as wide as a bigint, so its index is bigger whatever the order. Random order adds half-empty pages after splits and writes scattered over the whole index, which stops fitting in memory as the table grows, and a larger WAL, because after each checkpoint the first change to a page writes the whole 8 KB page (full_page_writes). Version 7 removes the second cost and keeps the first.
The choice: bigint identity for internal keys; UUID v7 when ids must be generated outside the database or merged across databases; UUID v4 only when unguessable, time-free ids matter more than write cost. If a public id must not reveal volume or creation time, keep a bigint primary key and add a separate random public id with a UNIQUE index.
Most schemas are built from a handful of shapes. Each has a standard layout whose keys and constraints carry the rules; pick a shape to see its tables.
parent_id, as the chat data does) is cheap to write and to move a subtree, and is walked with a recursive CTE (section 5). Trees read far more than written are often stored as a materialised path ('1/7/12': a subtree is a prefix match, a move rewrites the subtree) or a closure table (one row per ancestor and descendant pair: a subtree is one join, an insert writes one row per ancestor).(series_id, ts), usually range-partitioned on time with Postgres declarative partitioning, so old data leaves by dropping or detaching a whole partition, which the documentation calls far faster than a bulk DELETE. Columnar engines for large-scale analytics are Analytics: columnar engines, DuckDB and the lakehouse; time-ordered indexes such as BRIN are Storage engines and indexes.Instead of DELETE, set deleted_at = now() and hide those rows, so a deletion can be undone and audited. The costs, as Brandur Leach catalogued in "Soft deletion probably isn't worth it" (2022): every query, report and join must remember WHERE deleted_at IS NULL (one that forgets shows deleted data); foreign keys stop meaning much (a live chat can point at a "deleted" user, and ON DELETE CASCADE never fires); UNIQUE constraints break (a user who deletes their account and signs up again collides with their own deleted row) unless the unique index is partial; and nothing is deleted, while privacy law's right to erasure (GDPR Article 17) requires real deletion of personal data, so you still need a purge job.
Use soft deletes only where users genuinely undo (a trash folder), with a view or row-level security policy that hides deleted rows by default and a scheduled hard delete after the retention period; elsewhere delete for real and copy the row into an archive or audit table first (a trigger, or the application in the same transaction), or keep history as an append-only event table.
Some data varies in shape row by row and is rarely queried field by field: an LLM's tool calls and their arguments, a provider's raw response, preferences, a webhook payload. A column per possible field would be mostly empty; a table per shape, dozens of tables. Postgres has json (the text exactly) and jsonb (a parsed binary form, read and indexed without re-parsing; the documentation: "most applications should prefer to store JSON data as jsonb"). -> returns a JSON value, ->> text, @> tests containment, and a GIN index (a generalised inverted index: for each key and value, the rows containing it) makes containment fast. SQLite stores JSON as text, with json_extract and, since 3.38.0, the same -> and ->>.
The Postgres version's last statement shows the planner using the GIN index (sequential scans switched off for the demonstration; at 2,000 rows a scan would be cheaper and the planner would choose it).
The root's Database atlas compares this with a document database: Postgres jsonb covers most document needs while keeping joins and constraints (Topic: databases, section 6).
A business product serves many customer organisations (tenants), and one bug in one query is enough to leak one tenant's rows to another. The default for most SaaS products is shared tables with a tenant_id column leading every key, index and foreign key (the "many tenants" shape above). Postgres row-level security (RLS) moves the tenant filter into the database: a policy adds its condition to every query and checks every write, using a setting the application sets per request. But superusers and BYPASSRLS roles always bypass it, and the table's owner bypasses it unless you run ALTER TABLE ... FORCE ROW LEVEL SECURITY (documentation), so the application must connect as a role that does not own the tables.
The composite foreign key (FOREIGN KEY (tenant_id, chat_id) REFERENCES chats (tenant_id, id)) is what stops a row pointing across tenants. With a connection pool, set the tenant with SET LOCAL inside each transaction so it cannot leak into the next request on the same connection (pooling is Running Postgres in production).
| Pattern | How | Good for | Costs |
|---|---|---|---|
Shared tables, tenant_id column ("pool") | Every tenant-owned table has tenant_id; every index and key starts with it | Many small tenants; the default for most SaaS products | Every query must filter by tenant; a noisy tenant affects others |
| Schema per tenant | Same tables in one Postgres schema per tenant | Tens to hundreds of tenants needing separation | Every migration runs N times; thousands of schemas strain the catalog and tooling |
| Database per tenant ("silo") | A separate database or server each | Few large tenants, regulated data, data residency | Cost and operations multiply; cross-tenant reports need a pipeline |
Real rows of the page's database: each thin slab is one message of user 7, grouped by chat (the number under each group is its message count); the coloured cap is her name stored on that row. The new name is illustrative.
The tempting first design is one wide table: every message row also carries its chat's title and its user's name, email and plan, so any screen is one query with no joins. It works until a fact changes. Column B depends on column A (a functional dependency, A → B) if knowing A fixes B: user_id → email. A candidate key is a minimal set of columns that fixes all the others. Storing a dependent fact beside something other than its key causes anomalies: an update anomaly (one fact in many rows; miss one and there are two versions), an insert anomaly (a fact cannot be stored without an unrelated one: a user who has sent no message has no row) and a delete anomaly (removing one fact removes another: delete a user's last message and their email is gone). Predict how many rows a rename must write in each design before Fig. 5 plays it on the real messages of Ines Novak (user 7): one rename, 59 rows to write in the wide table, 1 in the normalised schema.
chat_log: each of user 7's 59 message rows, grouped by her 7 chats, carries her name, email and plan; the cap on each row is her name.users; each chat is one row of chats; a message row stores only chat_id and reaches the name by a join through chats.user_id.UPDATE users SET name = ... WHERE id = 7: one row, whatever the number of messages, and every message shows the new name through the join. The careless code path has nothing left to miss.users like any other.Each form adds one rule (William Kent's four-page guide, CACM 1983 is still the best short explanation). A schema designed from entities and relationships (section 7) is usually in BCNF already; the forms are most useful as a checklist when reviewing a table that "has everything in it".
| Form | Rule | A violation in the chat product | The anomaly it causes | The fix |
|---|---|---|---|---|
| 1NF | Each cell holds one value; no repeated groups of columns. | chats.tags = 'sql,python', or columns tag1, tag2, tag3. | "Chats tagged sql" needs string matching; a fourth tag needs a schema change; no foreign key can check a tag. | A table chat_tags(chat_id, tag), one row per tag. |
| 2NF | In a table with a multi-column key, no column depends on only part of the key. | chat_members(chat_id, user_id, role, user_email): the email depends on user_id alone. | Update: an email change must touch every membership row. | Keep email in users. |
| 3NF | No column depends on another non-key column. | users(id, country, country_name): the name depends on the country code; or messages(id, chat_id, chat_title). | Update: renaming a country or a chat touches many rows; insert: no country without a user. | A countries table; keep the title in chats. |
| BCNF | Every column set that determines another column is a candidate key. | Reviews (chat_id, language, reviewer), each chat has one reviewer per language, each reviewer handles one language. Key (chat_id, language); but reviewer → language and reviewer is not a key. | A reviewer switching language must be updated in every row, and a reviewer with no chats yet cannot be recorded. | reviewers(reviewer, language) and chat_reviews(chat_id, reviewer). |
Codd defined the first normal form with the relational model in 1970, the second and third in 1971, and Boyce and Codd the stricter BCNF in 1974 (history summarised on Wikipedia). Beyond BCNF, the fourth and fifth normal forms deal with independent multi-valued facts in one table (a user's languages and devices stored as all combinations); Kent's guide covers them.
Denormalisation is storing a derived or copied fact on purpose to make reads cheaper. It is right when a hot read path would otherwise do expensive work on every request and you accept owning the copy, and every copy needs three things: an owner, a mechanism that keeps it in step, and a check that it still is.
chats.message_count), kept by a trigger (code the database runs on every insert, below) or by the application in the same transaction as the write.CREATE MATERIALIZED VIEW): a stored query result, refreshed on a schedule; stale between refreshes.The check is a reconciliation query that compares the copy with the source and should return nothing, run on a schedule with an alert on any row: SELECT id FROM chats c WHERE message_count <> (SELECT COUNT(*) FROM messages m WHERE m.chat_id = c.id) (the Exercises lab has one, "Find the impossible rows").
A rule written only in application code ("a chat always has an owner", "a balance is never negative") holds only while every code path, script, migration and teammate remembers it. The schema is the one place every write must pass through, so write every rule you can as a constraint; each also tells the next reader something true about the data, which a comment cannot guarantee.
CHECK (balance >= 0), CHECK (role IN ('user', 'assistant')).ON DELETE: CASCADE (deleting the parent deletes the children: right for a folder's links), RESTRICT (refuse while children exist: right for anything with history, such as messages), SET NULL. SQLite enforces foreign keys only after PRAGMA foreign_keys = ON (SQLite docs); Postgres always does.WITHOUT OVERLAPS primary keys and unique constraints for the same idea (release notes).Bad writes against the chat schema and the constraint that refuses each; the error names are Postgres's. Without them, every one of these rows would be accepted and found months later, after reports were built on it.
What constraints cost: a check on every write (small; a foreign key check is an index lookup on the parent), and adding one to a big live table needs care (section 11). Their absence costs far more.
A user in Tokyo asks for "today's messages"; the server runs in UTC; daylight saving moves clocks in some zones twice a year. Postgres has timestamp (a date and wall-clock time with no zone) and timestamptz (an absolute instant). Despite its name, timestamptz stores no zone: the input is converted to UTC and stored as UTC, and on output it is shown in the session's TimeZone setting (documentation). So the same instant prints differently in different sessions, while a plain timestamp prints the same digits everywhere and means nothing on its own. Interval arithmetic respects the calendar: across the night New York moves its clocks forward, adding 1 day keeps the wall-clock time while adding 24 hours lands an hour later.
timestamptz (the Postgres wiki's Don't Do This page says not to use plain timestamp for them); keep sessions in UTC; convert to the user's zone (an IANA name such as Asia/Tokyo, never a fixed offset like +09:00, which ignores daylight saving) only when bucketing by day or displaying; store a user's zone as a column if reports need their days. date for calendar dates with no time (a birthday). SQLite has no date type: store ISO 8601 text in UTC or integer Unix seconds, consistently.A wall-clock time that never happened (inside the skipped hour) is moved forward:
The chat data stores UTC wall-clock times in a plain timestamp (as many real systems do), so a per-user day needs two conversions: declare the value as UTC, then convert to the user's zone.
A column with a fixed set of values (a plan, a role, a status) can be declared three ways. A Postgres enum type is compact (4 bytes) and sorts in declared order, and a value can be added, but "existing values cannot be removed from an enum type, nor can the sort ordering of such values be changed" short of recreating the type. A text column with a CHECK (what the chat schema uses for role) is portable and easy to change. A lookup table with a foreign key is the most flexible: adding a value is an INSERT, and the value can carry data (a price, a label, a sort order, an "active" flag). Rule of thumb: CHECK for small sets owned by the code (role); a lookup table when the values carry data or are managed by people (plans, countries); an enum only for sets that will genuinely never shrink.
Names are read far more often than written, by people and by tools. The conventions most Postgres teams converge on:
"ChatTags" must be quoted forever (the wiki: don't use upper case names).users, messages) or singular, but one choice for the whole schema. The primary key id; foreign keys <singular>_id (user_id); timestamps <verb>_at (created_at, deleted_at) as timestamptz; booleans as is_ or has_ predicates.user, order, group need quoting); no abbreviations only the author knows.chats_user_id_fkey, messages_chat_id_idx): migration tools and error messages refer to them by name, and Alembic cannot detect changes to anonymous constraints.The schema must change as the product does, but the database is serving traffic, several copies of the application are running, and during a deploy old and new code run at the same time. A migration is a small versioned script that moves the schema from one version to the next, kept in the repository beside the code that needs it; a migration tool applies the scripts in order and records which ran in a table of its own (Alembic's is alembic_version), so every environment, from a laptop to production, reaches the same schema by the same steps. Two rules: never edit a migration that has run somewhere else (write a new one), and never change production's schema except through one.
Postgres protects a table's definition with table locks. A SELECT takes the weakest, ACCESS SHARE; INSERT, UPDATE and DELETE take ROW EXCLUSIVE; most ALTER TABLE forms take the strongest, ACCESS EXCLUSIVE, which "guarantees that the holder is the only transaction accessing the table in any way": while it is held, even reads wait. What separates a safe change from an outage is how long that lock is held. Measured on a 2,000,000-row copy of messages (all 21 changes in ALTER TABLE, measured):
clock_timestamp(), a stored generated column, most type changes (integer to bigint, text to varchar(200)). Seconds here, hours on a big table.Each slow form has a safe recipe: CREATE INDEX CONCURRENTLY (builds without blocking writes, slower, cannot run in a transaction); ADD CONSTRAINT ... NOT VALID (instant, checks only new rows) then VALIDATE CONSTRAINT (checks old rows under a lock that blocks neither reads nor writes); for NOT NULL, a validated CHECK (col IS NOT NULL) lets SET NOT NULL skip its scan (PostgreSQL 12 and later; PostgreSQL 18 also accepts NOT VALID on not-null constraints directly); for a volatile default, add the column nullable, backfill in batches, then set the default.
Locks are granted in order. If a long transaction holds even the weakest lock on a table (a slow report, or a request that opened a transaction and is waiting on a model call), an ALTER TABLE asking for ACCESS EXCLUSIVE must wait for it, and every query that arrives after the ALTER queues behind it, because granting them would starve the ALTER. A change that takes a millisecond blocks all traffic to the table for as long as the oldest transaction lasts. Three real runs on the 2,000,000-row table: one long transaction holding the table for 4 seconds, one ADD COLUMN ... DEFAULT 0 (metadata only), and seven ordinary point reads arriving every half second. Predict the worst read's wait in each before you play it. (Finding the blocker on a live server and making schema changes safe in production are Running Postgres in production's section 8.)
The run, in stretches
messages_big and stays open for 4 s (a slow report, or a request waiting on a model call), holding the weak ACCESS SHARE lock.pg_locks snapshot at 2.2 s (under the chart) shows them waiting.SET lock_timeout = '500ms'.Bound the wait, do not hope. Set lock_timeout in every migration session (SET lock_timeout = '500ms'): the ALTER gives up instead of queueing indefinitely (documentation) and the migration retries after a pause, so readers wait at most the timeout. Set statement_timeout on backfills, keep application transactions short, and set idle_in_transaction_session_timeout so a forgotten open transaction cannot hold locks forever. (Lock modes in general are Transactions and concurrency.)
During a rolling deploy old and new versions run together, so every intermediate schema must work with both. Expand and contract (also called parallel change) splits a breaking change into backward-compatible steps, each deployed on its own. RENAME COLUMN itself is instant, but it breaks every running instance that still uses the old name; that, not the lock, is why a rename takes six steps:
chats.title exists and every running copy of the application (v1) reads and writes it.ALTER TABLE chats ADD COLUMN name text; is metadata only, so ACCESS EXCLUSIVE is held for milliseconds (with lock_timeout set). v1 does not know the column exists and keeps working.UPDATE chats SET name = title WHERE id BETWEEN $1 AND $2 AND name IS NULL. Now every row has name.ALTER TABLE chats DROP COLUMN title; a release or more later. Each step can be rolled back by redeploying the previous code; RENAME COLUMN in one step would have broken every running v1 at once.The models gained a chats.pinned flag and the foreign-key index from section 2; this is the script Alembic drafted and the SQL it would run (alembic upgrade head --sql prints instead of executing, the way to review a migration):
The index is created without CONCURRENTLY, which blocks writes to messages while it builds. On a big table, edit the script to use op.create_index(..., postgresql_concurrently=True) inside an autocommit_block(), because Postgres refuses CREATE INDEX CONCURRENTLY inside a transaction. Autogenerate also cannot detect renames (it sees a drop and an add), so every draft is reviewed.
| Tool | Style | Latest | Notes |
|---|---|---|---|
| Alembic | Versioned scripts in Python, with autogenerate | 1.20.0 (2026-09-11, PyPI) | The SQLAlchemy project's tool; compares your models with the database and drafts the script. |
| Django migrations | Versioned, generated from models | Django 6.1.1 (2026-09-02, PyPI) | Built into Django; same review rule. |
| Flyway | Versioned SQL files | 13.9.0 (2026-10-01) | Plain SQL, language-agnostic, common in Java shops. golang-migrate (4.20.1) is the Go equivalent. |
| Atlas | Declarative: you write the desired schema, it computes the plan | v1.3.0 (2026-08-02) | "Define your desired state, Atlas computes the plan"; also lints plans for destructive changes. |
| pgroll | Expand and contract, automated | v0.16.3 (2026-09-08) | Serves the old and new schema at once through views during the change, so it is reversible. |
| Squawk | Linter, not a runner | v2.67.0 (2026-10-04) | Flags migrations that take dangerous locks or rewrite tables; runs in CI. Rails has strong_migrations for the same job. |
| sqlc | Not a migration tool | v1.31.1 (2026-04-22) | Compiles your SQL queries into typed code (Go, Python, Kotlin and more); it reads your migration files to learn the schema. |
Versions read from PyPI and the projects' GitHub release pages on 2026-10-04.
Much production SQL is not written by hand: an ORM (object-relational mapper) generates it from classes, and LLMs generate it from questions (text-to-SQL features, agents with a database tool). Both produce SQL that runs; the two failures that matter are SQL that is slow by shape (too many round trips) and SQL that is wrong or unsafe (it returns plausible numbers, or does more than it should). This section shows each on the chat data, then the checks that catch them.
An ORM maps tables to classes and rows to objects, writes the SQL, and tracks changes so it can save them; in Python the standard is SQLAlchemy (2.1.3, released 2026-10-03 per PyPI), whose 2.x style declares typed models and builds queries with select(). What it hides is the SQL and, above all, the number of round trips (one request and its reply over the network: a fraction of a millisecond to a millisecond or two inside one data centre, paid per query however small):
class Chat(Base):
__tablename__ = "chats"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
title: Mapped[str | None]
created_at: Mapped[datetime.datetime]
messages: Mapped[list["Message"]] = relationship(order_by="Message.id")
chats = session.scalars(select(Chat).order_by(Chat.created_at.desc()).limit(50)).all()
for c in chats:
print(c.id, len(c.messages)) # each c.messages here is a new query
The loop runs 1 query for the chats and then, because relationships load lazily by default (only when first touched), 1 more per chat: N+1 in total. The SQLAlchemy documentation names it as "one of the most common issues referred to in object relational mapping". It is invisible in development, where the database is on the same machine and there are ten rows, and grows linearly with the page size and the network distance. Predict how many times slower the lazy loop is at N = 200 through 1 ms of network, then pick it:
The fixes: selectinload(Chat.messages) loads all the children with a second query WHERE chat_id IN (...), 2 queries whatever N (the documentation calls it "the most simple and efficient way to eagerly load collections"); joinedload(Chat.messages) uses one LEFT JOIN, but each chat's columns repeat once per message (fan-out again), so it suits many-to-one (a message's chat) better than one-to-many; raiseload("*") in tests or on hot paths turns any accidental lazy load into an error, so N+1 cannot creep back; or write one SQL statement that aggregates in the database and returns only what the screen needs. In practice: the ORM for ordinary reads and writes, hand-written SQL (SQLAlchemy Core, text(), or sqlc) for reports and anything performance-critical, and paginate by key, not by OFFSET (Building a backend API measures why).
PostgreSQL 16.2, SQLAlchemy 2.1.3, psycopg 3.3.6, the chat data with an index on messages.chat_id. Each bar is the median of 30 runs of "load the N most recent chats, with each one's message count and last message"; every SQL statement sent was counted. "Through 1 ms of network" sends the same traffic through a small proxy that adds 0.5 ms each way, about the round trip between two machines in one region. All four return identical results.
Less boilerplate for create, read, update and delete; queries composed from Python pieces; parameters bound safely by default; an identity map (one object per row per session); a unit of work (changes flushed in a valid order); and models Alembic can diff.
If a program builds SQL by pasting input into the query text, the input can change the query's meaning: SQL injection, still near the top of the OWASP list of web risks. A real "find my account" lookup in the page's database; try the inputs:
The fix: parameterised queries. Write placeholders (? in SQLite, %s in psycopg, :name in SQLAlchemy's text()) and pass the values separately; the value is then data, never SQL, and an apostrophe in a real name stops being a bug too. Psycopg 3 "sends the query and the parameters to the server separately"; its rule is "Never use % or + to merge values into queries".
# wrong: the input becomes part of the SQL
cur.execute(f"SELECT id FROM users WHERE email = '{email}'")
# right: the input is a value
cur.execute("SELECT id FROM users WHERE email = %s", (email,))
# SQLAlchemy
session.execute(text("SELECT id FROM users WHERE email = :e"), {"e": email})
Identifiers cannot be parameters: a table name, a sort column or ASC/DESC from input must come from an allow-list in your code, or be quoted with psycopg.sql.Identifier (psycopg.sql). An ORM protects you only while you use it as intended: text() or raw SQL built with f-strings is as vulnerable as anything else. Defence in depth: the application's role gets only the privileges it needs (no DDL, no superuser), and row-level security (section 8) limits what a successful injection could read.
LLM-written SQL is untrusted input of the same kind as user input, and like ORM SQL it fails in the ways this page has shown: it runs and returns plausible numbers. The checks, each pointing at the section that explains it:
create_engine(..., echo=True) in development, per-request query counts in tracing (Observability), query counts asserted in tests for important endpoints.statement_timeout and a row limit, never as the application's owner role; on the production engine's dialect (section 1).Safety boundaries (right) hold even when every review (left) misses something. Text-to-SQL itself (schema retrieval, how the model is prompted) is GraphRAG and structured retrieval; agent tool security is Agent security.
When it is correct, make it fast: Query planning and performance and Transactions and concurrency are the next pages.
Write the query, press Check, and the page's own database grades it: it runs your query and the reference solution on fresh copies of the same data and compares the results.
The data is the Reading tab's: users(id, email, name, plan, country, created_at), chats(id, user_id, title, model, created_at), messages(id, chat_id, parent_id, role, content, tokens, created_at), credits(user_id, balance). Timestamps are text like '2026-03-15 10:00:00' (SQLite has no date type). Grading rules: the last statement that returns rows is compared; column names do not matter but the number and order of columns do; rows must match exactly (numbers to 6 decimal places), in order only where the exercise says "in order", "by id" or similar. Levels: 1 warm-up 2 core 3 harder 4 pro. Your progress is kept in this browser only.
Shown after you check, or with the solution.
One correct answer; many others pass. The solutions were also run offline in Python's SQLite (src/ex/check.py) and in this page's engine (src/check_page.mjs).
Twenty-one common schema changes, each run on a copy of the chat messages grown to rows ( of table data) on PostgreSQL 16.2, with what it actually did.
How it was measured (src/pg/measure_alter.py): each change ran inside its own transaction; while that transaction was still open, pg_locks was read for the locks it held on the table, and a second session tried a point SELECT and an INSERT with lock_timeout = 300ms to see whether they were blocked; the table's file node was compared before and after to see whether the table was rewritten; then the transaction was rolled back so every change started from the same table. CREATE INDEX CONCURRENTLY cannot run in a transaction, so it was watched from a second session while it ran. Times are medians of 3 runs on a laptop. Lock names: AccessExclusive blocks everything, reads included; ShareRowExclusive and Share block writes but not reads; ShareUpdateExclusive blocks neither, only other schema changes and VACUUM (PostgreSQL table-level locks).
pg_blocking_pids, is Running Postgres in production section 8, the lock queue). A rewrite or a scan grows with the table: the "your table" column scales the measured time linearly with the row count, which is a rough guide only (it ignores memory, disk speed, indexes and concurrent load). Plan with a measurement on a production-sized copy.Times are reading estimates. Pages in this knowledge base open in Notion.
28 graded exercises, warm-up to gaps-and-islands, checked by the page's database. 1 to 3 hours
21 schema changes: locks, rewrites, measured times, safe recipes, scaled to your table. 15 min
The overview: one chat product's data from a file to a fleet; tabs SQL playground (12 beginner lessons on this data), Query plans, Database atlas. 29 min
ACID, MVCC, isolation anomalies, locks: what happens when two writes meet. The natural next page. Child page, about 43 minutes.
EXPLAIN, statistics, join algorithms, slow queries: making the correct query fast. Child page, about 45 minutes.
Pages, B-trees, the WAL, index types: the mechanism behind section 7's key measurement. Child page, about 42 minutes.
Backups, replication, vacuum, upgrades, connection pooling. Child page, about 43 minutes.
When a document, key-value, wide-column or graph model fits better than tables. Child page, about 46 minutes.
Where denormalised wide tables belong. Child page, about 46 minutes.
Read replicas, sharding, distributed SQL; why the shard key is a modelling decision. Child page, about 45 minutes.
Every cache layer, Redis eviction measured on real traffic, invalidation, and the KV, prompt and semantic caches. Child page, about 43 minutes.
Inverted indexes, BM25, embeddings, ANN indexes measured in pgvector, filtered and hybrid search. Child page, about 33 minutes.
The service in front of these tables: idempotency keys built on unique constraints, cursor pagination measured. 32 min
The outbox pattern and change data capture: keeping denormalised copies in step. 40 min
Seeing query counts and slow queries per request in traces. 39 min
Tests for code that talks to a database, data tests, CI. 46 min
The system around the database, on the same chat product. 25 min
The official tutorial; chapters 2 and 3 cover queries, joins, aggregates, views, foreign keys, transactions and window functions. 1.5 hours
Graded exercises on a country-club schema, from basics to recursive queries, in a live Postgres. 3 to 6 hours
Short interactive lessons for the very first steps. 1 hour
The clearest precise description of frames, RANGE against ROWS, and EXCLUDE. 25 min
Each modern SQL feature (FILTER, window functions, MERGE, JSON) with which databases support it. browse
Free book on SQL indexing for developers; read after this page and before the query planning page. 3 hours
Every normal form with one example each, in four pages. 20 min
The paper that started it; section 1 is readable today. 45 min
NOT IN, plain timestamp, serial, upper-case names, money, varchar(n) and more, each with why and when it is fine. 25 min
Read section 5.4 (v4), 5.7 (v7) and 6 (best practices). 25 min
The costs of deleted_at, and the deleted-records table alternative. 10 min
Policies, USING against WITH CHECK, who bypasses them. 20 min
Chapter 2 (data models and query languages) puts relational, document and graph models side by side. 1.5 hours
The table of lock modes and what each conflicts with; which command takes which. 20 min
Which forms rewrite, which scan, NOT VALID and VALIDATE. 20 min
The lock queue outage, told from production (written for 9.4; see the correction box in section 11). 15 min
A catalogue of dangerous operations and the safe way to do each; useful whatever your language. 25 min
The checks a migration linter runs, each with its reason. 20 min
Setting up migrations for a SQLAlchemy project; then the autogenerate page. 40 min
Models, sessions and select() in the 2.x style used in section 12. 30 min
Lazy, selectin, joined and raise loading, and when to use each. 30 min
Parameterised queries first, then allow-lists, least privilege. 20 min
Placeholders, the rules, and psycopg.sql for identifiers. 15 min
Built from src/: the examples were run on PostgreSQL 16.2 (pgserver wheel) and SQLite on 2026-10-04; the in-page engine is sql.js 1.14.2 (MIT; SQLite is public domain), shared with the root page. Reproduce with the commands in src/README.md.