SQL and data modelling: queries, joins, schema design, normalisation, migrations

What a query means and what a schema promises: the evaluation order and NULL, joins drawn as pairs, grouping and windows, recursion, upserts, keys, common shapes, normalisation, constraints, safe migrations, and checking SQL an ORM or LLM writes. Every query runs in a real database inside the page beside its PostgreSQL 16 result; timings measured on a laptop. A child of Topic: databases. Data as of October 2026. Reading: 48 min, plus 24 in closed details.

The idea in one screen

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;
  1. FROM: every pair. 50 users down one edge, 200 chats along the other: logically a join starts from all 10,000 pairs, one cell each of the glass plate.
  2. ON keeps the true pairs. 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).
  3. WHERE keeps 90. Only the pairs where c.model = 'mini' is true pass (section 1): 90 of the 200; the other 110 vanish.
  4. GROUP BY folds, ORDER BY sorts. Each plan's pairs collapse into one row with its count: free 47, pro 37, team 6, sorted by the count. Three rows out (section 3).
  5. A write meets the rules. The foreign key on 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.

Three-valued logic
a comparison with NULL is neither true nor false but unknown; WHERE keeps only true.
Semi, anti join
keep a row if some (semi) or no (anti) matching row exists, without repeating it per match.
Fan-out
a join that repeats a row once per matching child, inflating counts and sums.
Window function
a value computed for each row from related rows (its window), without collapsing them.
CTE
a named step of a query, WITH name AS (...); recursive when it refers to itself.
Upsert
insert, or update if the key exists, in one atomic statement.
Functional dependency
A → B: knowing column A fixes column B.
Expand and contract
a breaking schema change split into backward-compatible steps.

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 whole page happens on these four tables: joins follow the arrows, rules sit on the columns

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.

1. Written in one order, evaluated in another; NULL is unknown

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.

A name exists only from the step that makes it: aliases from SELECT, aggregates from GROUP BY

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.

Unknown spreads through AND and OR, and only TRUE passes a filter

ANDTFU
TTFU
FFFF
UUFU
ORTFU
TTTT
FTFU
UTUU
xNOT xx = NULLx IS NULL
TFUF
FTUF
UUUT

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).

The logical order is not the execution order
The pipeline defines what the answer must be, not how it is computed. The planner (the part of the database that chooses how to run a query) may filter before joining, use an index instead of reading everything, or stop early under a LIMIT, as long as the result is the same. How it chooses, and how to read its plan, is Query planning and performance and the root's Query plans tab.

2. Joins: every pair, filtered

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.

  1. CROSS keeps every pair. No condition: 5 × 3 = 15 rows. On the chat data, 50 users and 200 chats make 10,000. Useful on purpose for a grid of every combination (report empty combinations as zero); a forgotten join condition does the same by accident.
  2. INNER keeps the true cells. 3 rows. Chen (IN is not a market) and Dara (no country) vanish; US appears twice because two users match it. A user with no chats disappears; a user with seven chats appears seven times.
  3. LEFT also keeps unmatched left rows. Every user, with NULLs for the market columns where no market matches: 5 rows ("every user, with their chats if any").
  4. RIGHT is the mirror image. Every market: Germany has no users and comes back with NULL user columns; Chen and Dara are gone again. 4 rows. Usually rewritten as a LEFT with the tables swapped.
  5. FULL keeps both sides. The unmatched users and the unmatched market: 6 rows, the join for reconciling two lists. SQLite gained RIGHT and FULL only in version 3.39.0, 2022-06-25.
  6. Semi join (EXISTS) keeps a row, once. 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.
  7. Anti join (NOT EXISTS) keeps rows with no match. Chen and Dara, 2 rows (also written as a LEFT JOIN keeping rows where the right key IS NULL). NOT EXISTS asks "is there a matching row?", so a NULL anywhere does not change its answer.
  8. NOT IN looks like the anti join, but is not. Dara is missing: her country is NULL, and NULL NOT IN (...) is unknown, not true. 1 row.
  9. Add one NULL market and NOT IN returns nothing. Every comparison against the NULL code is unknown, so no row can pass: 0 rows. NOT EXISTS still returns Chen and Dara.

Three more runnable joins: FULL, CROSS for empty combinations, a self join, anti join three ways (examples)

A self join joins a table to itself under two names; with parent_id, each assistant reply sits next to the prompt it answers.

Three joins that run and return the wrong answer

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.

Fan-out: joining down two levels repeats each chat once per message

What a join costs, and the index this page owns
How the database finds matching pairs (a loop, a hash table, or two sorted inputs) is on Query planning and performance. One modelling consequence belongs here: Postgres indexes primary keys and UNIQUE columns automatically, but not foreign key columns; the documentation on foreign keys recommends indexing the referencing column yourself, because joins and deletes of the parent need it.

3. Grouping: many rows become one per group

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:

  1. Sixteen rows. The real messages of chat 11, 8 from the user and 8 from the assistant, each bar as tall as its tokens.
  2. GROUP BY role splits them. The user rows go to one group, the assistant rows to the other (PARTITION BY role splits a window the same way).
  3. Each group folds into one row. 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.
  4. A window keeps every row. 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.
  5. ORDER BY inside OVER: a running total. 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).

Subtotals with ROLLUP, CUBE and GROUPING SETS, and the AVG type difference (depth)

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.

4. Window functions: a value per row from its neighbours

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).

  1. The rows, in window order. The 16 messages of chat 11 ordered by id (back row): one partition here. Each function below is computed for every row in turn; the glass box is the frame it sees for the current row, the front row its results.
  2. SUM(tokens) OVER (ORDER BY id). The default frame runs from the first row to the current one, so the sum is a running total: 103, 548, 649 ... 4,303.
  3. AVG over ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. A three-row frame slides along: 103.0, 274.0, 216.3 ... 261.0. Near the start the frame is shorter, which is why the first values are noisier.
  4. LAG(tokens) reads the previous row. The first row has none, so it gets NULL. Subtracting timestamps the same way gives the gap between messages.
  5. RANK() OVER (ORDER BY tokens DESC). No frame: the rank counts the rows that sort before this one (lit), plus one. The 889-token reply ranks 1, the 16-token message 16; ties would share a rank and leave a gap.
  6. LAST_VALUE(tokens) with the default frame. The frame ends at the current row, so the "last value" is always the current row's own tokens: the front row copies the back row. Almost never what was meant.
  7. LAST_VALUE over the whole partition. 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.

More runnable windows: ranks on ties, LAG for gaps, running totals, LAST_VALUE (examples)

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.

5. CTEs and recursive queries

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.

Each iteration joins only the rows the last one added, and stops when it adds none


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.

  1. The anchor runs once. Message 1682, the last of chat 11, enters the result and becomes the working table (outlined).
  2. Iteration 1 joins only the working table. 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.
  3. Iterations 2 to 14, one parent each. 1680 back to 1667 (1666 and 1668 belong to other chats); each iteration adds exactly the row the last one pointed at.
  4. Iteration 15 reaches the first message. 1665 enters the result at depth 15; its parent_id is NULL.
  5. Iteration 16 adds nothing, so it stops. The join is on 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).

When recursion goes wrong
A recursive query on a cycle (a message that is its own ancestor through bad data) never ends: guard with a depth limit (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.
Two more recursive examples: an org chart with depth and path, filling empty days (examples)

6. Writes: upserts, idempotency, MERGE, set operations

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.)

Two requests at once: read-then-write loses one, one ON CONFLICT statement counts both

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.

MERGE, runnable; set operations (UNION, UNION ALL, INTERSECT, EXCEPT) (examples)

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.

7. Entities, relationships and keys

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):

One to many

A user has many chats; a chat has one user. The foreign key goes on the "many" side: chats.user_id. Most relationships.

Many to many

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).

One to one

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.

Natural or surrogate key

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, UUID v4 or UUID v7

  • bigint identity (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).
  • UUID version 4: 16 bytes, 122 bits of them random. Any machine can generate one without asking the database (clients create ids offline, ids from separate databases never collide, nobody can guess the next one), but each new key lands at a random place in the index.
  • UUID version 7 (RFC 9562, May 2024): the Unix time in milliseconds in the first 48 bits, random bits after. Generated anywhere like v4, but new keys sort after old ones like bigint; it reveals when a row was created. PostgreSQL 18 (released 2025-09-25) has a built-in 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:

Random UUID v4 keys cost a bigger index and more WAL than v7 for the same rows measured

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.

Reading the measurement: two effects are mixed in it (depth)

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.

8. Modelling common shapes

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.

  • Many to many: a join table whose primary key is the pair; facts about the relationship live on it (section 7).
  • Trees: an adjacency list (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).
  • Time series (usage per minute, model latency, token counts): append-only rows keyed by (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.
  • Soft deletes and JSON columns have costs that are easy to miss; they follow.

Where the keys go decides what the database can enforce

Soft deletes and their cost

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.

JSON columns: jsonb

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).

Use jsonb when

  • the shape genuinely varies, or belongs to someone else (an API response kept for audit);
  • you read the document whole and filter on a few fields at most;
  • it is an attachment to a row that has real columns for everything you join, group or constrain on.

Use columns when

  • you join on it, group by it, or need a foreign key or a CHECK on it;
  • every row has the field (a "flexible" document where every row has the same keys is a table in disguise, without types or constraints);
  • you update single fields often (jsonb is rewritten whole on update).

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).

Many customers in one database

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.

RLS runnable, connection pools, and the three tenancy patterns compared (depth)

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).

PatternHowGood forCosts
Shared tables, tenant_id column ("pool")Every tenant-owned table has tenant_id; every index and key starts with itMany small tenants; the default for most SaaS productsEvery query must filter by tenant; a noisy tenant affects others
Schema per tenantSame tables in one Postgres schema per tenantTens to hundreds of tenants needing separationEvery migration runs N times; thousands of schemas strain the catalog and tooling
Database per tenant ("silo")A separate database or server eachFew large tenants, regulated data, data residencyCost and operations multiply; cross-tenant reports need a pipeline

Fig. 5 · user 7, one wide table against three tables

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.

9. Normalisation: one fact in one place

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.

  1. The wide table. 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.
  2. A correct rename writes 59 rows. To stay correct, the UPDATE must find and rewrite every one of them, in every chat, in one transaction.
  3. A buggy path writes 5. Code that updates "the current chat's rows" (chat 22) rewrites 5 rows; the other 54 still say "Ines Novak". Nothing failed and nothing warned.
  4. Two answers, and two more anomalies. Ask "what is user 7's name?" and the data gives two answers: the update anomaly, one fact stored 59 times disagreeing with itself. A user who has not sent a message has no row at all (insert anomaly), and deleting Ines's messages would delete her email too (delete anomaly).
  5. Normalise. Her name moves into one row of 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.
  6. The same rename writes 1 row. 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.
  7. A user exists without messages. Six of the 50 users in this data have never opened a chat, and they are stored perfectly well, as rows of users like any other.

The normal forms, by the anomaly each removes

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".

FormRuleA violation in the chat productThe anomaly it causesThe fix
1NFEach 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.
2NFIn 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.
3NFNo 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.
BCNFEvery 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).
History, and beyond BCNF (depth)

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.

When to denormalise, and how to keep the copy right

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.

  • Counters and totals on the parent (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.
  • Materialised views (CREATE MATERIALIZED VIEW): a stored query result, refreshed on a schedule; stale between refreshes.
  • Read models and search indexes built from the change stream (the outbox and change data capture patterns are on Queues, streams and async work); caches are Caching.
  • Analytics: wide denormalised tables in a columnar store, rebuilt from the normalised source (root section 5; Analytics: columnar engines, DuckDB and the lakehouse).

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 copy that is not denormalisation
A snapshot of a historical fact is a different fact, not a copy: the price a customer paid (not today's price), the model that produced a message (not the chat's current model), the billing address on an invoice. Storing it on the row is correct normalised design; looking it up "live" would be the bug.

10. Constraints and types: correctness the database enforces

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.

  • NOT NULL on everything that must exist; nullable should be a decision, not a default.
  • CHECK for value rules: CHECK (balance >= 0), CHECK (role IN ('user', 'assistant')).
  • UNIQUE for natural keys, and partial unique indexes for rules over a subset of rows: "at most one pinned chat per user", "one live account per email" (soft deletes, section 8).
  • FOREIGN KEY with a deliberate 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.
  • Exclusion constraints (Postgres) for "no two rows overlap": no two active subscriptions of one user with overlapping date ranges (documentation). PostgreSQL 18 added WITHOUT OVERLAPS primary keys and unique constraints for the same idea (release notes).

Each constraint refuses one kind of bad row at the moment it is written

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.

Types are constraints too: time

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.

The rule for time
Store instants as 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.
Time zones, runnable: two sessions, the 23-hour day, counting a day in Tokyo (examples)

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.

Fixed sets of values: enums, CHECK lists and lookup tables (depth)

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.

Naming conventions (depth)

Names are read far more often than written, by people and by tools. The conventions most Postgres teams converge on:

  • lower_snake_case for everything. Postgres folds unquoted names to lower case, so a table created as "ChatTags" must be quoted forever (the wiki: don't use upper case names).
  • Tables plural (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.
  • No reserved words (user, order, group need quoting); no abbreviations only the author knows.
  • Name constraints and indexes explicitly (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.

11. Migrations: changing a schema that is in use

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.

Every ALTER TABLE takes a lock

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):

  • Metadata-only changes take milliseconds: adding a nullable column, adding a column with a constant default (since PostgreSQL 11 the default is stored once in the catalog, not written to every row), dropping or renaming a column, changing a default, widening a varchar.
  • Rewrites hold ACCESS EXCLUSIVE for the whole copy: a volatile default such as clock_timestamp(), a stored generated column, most type changes (integer to bigint, text to varchar(200)). Seconds here, hours on a big table.
  • Scans hold the lock while they check every row: SET NOT NULL, ADD CHECK, ADD FOREIGN KEY (which takes SHARE ROW EXCLUSIVE: reads continue, writes wait).

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.

Older guides are out of date on two points
Many guides still say adding a column with a default rewrites the table; that stopped being true for constant defaults in PostgreSQL 11 (2018), and the measurement agrees ( ms on 2,000,000 rows). GoCardless's widely shared "Zero-downtime Postgres migrations: the hard parts" was written against PostgreSQL 9.4 (its footnotes say so) and says adding a foreign key takes ACCESS EXCLUSIVE locks on both tables; PostgreSQL 9.5 reduced the lock level of foreign key commands, and current Postgres takes SHARE ROW EXCLUSIVE on both, which was measured here: reads continue, writes wait. Its central lesson, the lock queue below, is still exactly right.

Without lock_timeout, reads wait behind the waiting ALTER for up to 3.26 s; with it, at most 0.27 s

long transactionALTER waiting, then doneALTER attempt that gave upread that waited over 100 msread served at once

The lock queue: how a 1 ms change causes an outage

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

  1. A long transaction holds the table. It has read 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.
  2. The ALTER asks and waits. At 0.5 s the migration asks for ACCESS EXCLUSIVE, which conflicts with every lock, so it waits for the long transaction.
  3. Every read queues behind the ALTER. Each new read needs only ACCESS SHARE, compatible with the long transaction, but it is queued behind the waiting ALTER: reads that normally take 1 ms wait. The pg_locks snapshot at 2.2 s (under the chart) shows them waiting.
  4. The commit releases everything at once. At 4.0 s the long transaction commits; the ALTER gets its lock and finishes in a millisecond; the queued reads run. All 7 reads were delayed, the first by 3.26 s, for a 1 ms change.

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.)

Fig. 6 · chats.title becomes chats.name, the code running throughout

Expand and contract: changes that never break running code

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:

  1. Start. chats.title exists and every running copy of the application (v1) reads and writes it.
  2. Expand: add the column. 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.
  3. Write both. Deploy v2, which writes title and name (or add a trigger that copies one to the other). During the rolling deploy v1 and v2 run together; both still read title, so both are correct. Only new rows have a name.
  4. Backfill in batches. Once no v1 is left writing title alone, copy the old rows a few thousand per transaction with a pause between batches, so no lock or replication lag builds up: UPDATE chats SET name = title WHERE id BETWEEN $1 AND $2 AND name IS NULL. Now every row has name.
  5. Read the new column. Deploy v3, which reads name and still writes both, so the v2 copies running beside it stay correct.
  6. Stop writing the old column once no running version reads it: v4 uses name only.
  7. Contract: drop it. 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.
What professionals do
Migrations in the repository, applied by CI/CD (automated testing and deployment) before the code that needs them; reviewed as SQL, not just as model diffs; linted (Squawk, strong_migrations); timed on a production-sized copy; run with lock_timeout and retries; one risky operation per migration; roll forward with a new migration rather than run "down" migrations in production, with backups and point-in-time recovery as the real safety net (Running Postgres in production).
What Alembic actually generated, and what a reviewer must catch (real output)

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 SQL it emits

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.

The migration tools, as of October 2026 (dated reference)
ToolStyleLatestNotes
AlembicVersioned scripts in Python, with autogenerate1.20.0 (2026-09-11, PyPI)The SQLAlchemy project's tool; compares your models with the database and drafts the script.
Django migrationsVersioned, generated from modelsDjango 6.1.1 (2026-09-02, PyPI)Built into Django; same review rule.
FlywayVersioned SQL files13.9.0 (2026-10-01)Plain SQL, language-agnostic, common in Java shops. golang-migrate (4.20.1) is the Go equivalent.
AtlasDeclarative: you write the desired schema, it computes the planv1.3.0 (2026-08-02)"Define your desired state, Atlas computes the plan"; also lints plans for destructive changes.
pgrollExpand and contract, automatedv0.16.3 (2026-09-08)Serves the old and new schema at once through views during the change, so it is reversible.
SquawkLinter, not a runnerv2.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.
sqlcNot a migration toolv1.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.

12. SQL that an ORM or an LLM writes for you

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.

The N+1 query problem

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).

Lazy loading pays one round trip per row; selectinload pays two in all measured

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.

What an ORM gives you in return (depth)

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.

SQL injection, live

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".

The same input is SQL on the left and a value on the right

String concatenation

Bound parameter

# 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.

Checking generated SQL

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:

  • Look at the SQL and count it: create_engine(..., echo=True) in development, per-request query counts in tracing (Observability), query counts asserted in tests for important endpoints.
  • Read it for the traps: a LEFT JOIN filtered in WHERE, NOT IN over a nullable column, fan-out in an aggregate, LIMIT without ORDER BY, a default window frame (sections 1 to 4).
  • Check the rows, not that it ran: write the expected result first (a count you know, a total from another source) and compare.
  • Run it as a read-only role, with row-level security, a statement_timeout and a row limit, never as the application's owner role; on the production engine's dialect (section 1).

Where each check sits between the generator and the data

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.

Depth: a review checklist

The mistakes this page teaches, one line each, with the habit that prevents it (review list)
  • A LEFT JOIN filtered in WHERE turns into an inner join: conditions on the right table go in ON (section 2).
  • NOT IN over a column that can be NULL returns no rows: use NOT EXISTS (section 2).
  • Aggregating across two joined child tables multiplies counts and sums: aggregate each child, then join (section 2).
  • LIMIT without ORDER BY, or ROW_NUMBER without a tie-breaker: rows can change between runs; order by something unique (sections 1 and 4).
  • Window frames left to the default: LAST_VALUE returns the current row, RANGE includes ties; write the frame you mean (section 4).
  • Read, then insert or update, in application code races: one atomic INSERT ... ON CONFLICT (section 6).
  • Plain timestamp for instants, fixed offsets for zones: ambiguous times and wrong day boundaries twice a year; timestamptz and IANA names (section 10).
  • A natural key (email) as the primary key; integer instead of bigint: keys that change or run out; surrogate bigint or UUID v7 plus UNIQUE on the natural key (section 7).
  • Copying facts without an owner: copies drift; a sync mechanism and a reconciliation query for each (section 9).
  • Rules only in application code; unindexed foreign keys: rules in the schema; index the referencing column of every foreign key you join on or delete through (sections 2 and 10).
  • Soft deletes everywhere by default: leaks deleted data, breaks unique constraints and foreign keys, erases nothing; only where users undo, with a partial unique index and a purge job (section 8).
  • A migration without lock_timeout; an index built without CONCURRENTLY: a queued ACCESS EXCLUSIVE lock blocks every query behind it, a plain CREATE INDEX blocks writes (section 11).
  • Renaming or dropping a column in one step breaks the old code still running during the deploy: expand and contract (section 11).
  • Lazy loading in a loop: N+1 queries, hundreds of milliseconds at 200 rows over 1 ms of network; selectinload, raiseload in tests, or one SQL query (section 12).
  • Building SQL with string formatting: injection, and broken queries for names with apostrophes; bound parameters, allow-lists for identifiers (section 12).
  • Testing on SQLite, running on Postgres: the dialects differ in ways that matter; test against the production engine (section 1).

When it is correct, make it fast: Query planning and performance and Transactions and concurrency are the next pages.