BEGINNERCHAPTER 02

The relational model and SQL: SELECT through JOIN

Relations, keys and NULL, then the whole join family, then how to read a result that is wrong before anyone else does

55 MINDATABASESUPDATED 2026-11-02
PREDICT

The orders table has 2 000 000 rows. Suppose customer_id were nullable and exactly one of them had customer_id NULL. How many rows does SELECT count(*) FROM customers WHERE id NOT IN (SELECT customer_id FROM orders) return as its count?

SQL is the only programming language most engineers use for twenty years without ever learning its model. You can go a long way by pattern-matching: SELECT ... FROM ... WHERE, add a JOIN when you need another table, add GROUP BY when the numbers need adding up. It works until the day it produces a wrong number that looks right, and that day is the subject of this chapter.

The model is small. Relations, keys, NULL, and the handful of operations that combine relations. Once you have it, every join is predictable before you run it: you know how many rows will come back, and you know what will happen to the rows that do not match. The lab runs twenty queries against the shop, from one table to a four-way join, and the last four are wrong on purpose so that you learn to see it.

Relations, tuples, attributes

Codd’s 1970 paper defines a relation as a set of tuples, each tuple being one value for each of a fixed list of named attributes. In table language: a table is a set of rows, each row has one value per column, and every column has a name and a type. Three properties follow from the word set, and all three are things SQL tables do not quite honour.

A set has no duplicates. Two tuples with identical values in every attribute are the same tuple. SQL tables are bags: INSERT the same row twice and you have two rows. The relational answer is a key, which we come to next; the SQL answer is a UNIQUE or PRIMARY KEY constraint that turns the bag back into a set.

A set has no order. There is no first row. SQL returns rows in whatever order the executor found fastest, which for a sequential scan is physical order on disk, which changes after an UPDATE moves a row or VACUUM reclaims space. The Postgres documentation for SELECT says this in one sentence: if ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. Code that relies on unordered results being stable works in development and breaks in production, usually after the table is big enough that a plan changes.

Every attribute value is atomic. A cell holds one value of its type, not a list. SQL bends this in both directions: Postgres has array and JSON columns, and most schemas have at least one comma-separated string someone regrets. The modelling chapter returns to this as first normal form.

The shop’s orders table is a relation over seven attributes: id, customer_id, status, total_cents, created_at, shipped_at, and the row’s identity is id. Two million tuples at scale 1.

Keys

A candidate key is a minimal set of attributes whose values identify one tuple. Minimal means you cannot drop an attribute and keep uniqueness. customers.id is a candidate key; so is customers.email, because the schema declares it unique. (id, email) is not a candidate key, because id alone does the job.

You pick one candidate key to be the primary key. The others become unique constraints. In the shop every table has a surrogate bigserial primary key, and customers.email and products.sku are the natural candidate keys kept as UNIQUE. The modelling chapter weighs natural against surrogate; for querying, what matters is that a key tells you the maximum number of rows a lookup can return. WHERE customers.id = 42 returns at most one row. WHERE customers.country = 'DE' returns up to 500 000.

A foreign key is a set of attributes in one relation whose values must appear as a candidate key in another. orders.customer_id references customers.id. The constraint means a join on those columns is safe to reason about: every order has exactly one customer, so joining orders to customers cannot change the number of order rows. That one fact is the key to reading join results, and it is the whole reason to declare foreign keys rather than leave them as a convention in application code.

The shop’s foreign keys form a tree. orders points at customers. order_items points at orders and products. payments points at orders. inventory points at products and shares its key with it, so it is one-to-one. Every join you write in this course walks an edge of that tree, and the direction you walk it decides how the row count changes.

customers 500korders 2Mpayments 2Morder_items 6Mproducts 50kinventory 50k1 : many1 : many1 : ~1many : 11 : 1

NULL and three-valued logic

NULL is not a value. It is a marker that a value is absent, and it is the single largest source of wrong answers in SQL. orders.shipped_at is NULL for every order that has not shipped. It does not mean “shipped at the epoch”, it does not equal another NULL, and it is not less than or greater than any timestamp.

Every comparison involving NULL evaluates to a third truth value, UNKNOWN. shipped_at = NULL is UNKNOWN. shipped_at <> NULL is UNKNOWN. NULL = NULL is UNKNOWN. WHERE keeps a row only when its predicate is TRUE, so a row whose predicate is UNKNOWN is dropped the same as FALSE. That is why WHERE shipped_at = NULL returns nothing and WHERE shipped_at IS NULL returns 300 000 rows.

The truth tables are where the surprises hide. TRUE OR UNKNOWN is TRUE. FALSE AND UNKNOWN is FALSE. But TRUE AND UNKNOWN is UNKNOWN and FALSE OR UNKNOWN is UNKNOWN. NOT UNKNOWN is UNKNOWN. The Predict question above is the practical consequence: one NULL inside a NOT IN list turns the whole predicate UNKNOWN for every row.

Postgres gives you the tools to be explicit. IS NULL and IS NOT NULL return TRUE or FALSE, never UNKNOWN. IS DISTINCT FROM is a <> that treats two NULLs as equal and a NULL against a value as different, so a IS DISTINCT FROM b is always TRUE or FALSE. coalesce(shipped_at, created_at) substitutes a value. And in ORDER BY, Postgres sorts NULLs as if they were larger than every value, so they come last in ASC and first in DESC unless you say NULLS FIRST or NULLS LAST.

Aggregates have their own rule: they ignore NULLs. count(shipped_at) counts shipped orders; count(*) counts all orders; avg(shipped_at - created_at) averages only over shipped orders and says nothing about the ones still waiting. The aggregation chapter builds on this.

SELECT, WHERE, ORDER BY, LIMIT

A single-table query has a fixed logical order of evaluation that is not the order you write it in:

written evaluated does
SELECT 5 pick and compute output columns
FROM 1 name the relation
WHERE 2 drop rows whose predicate is not TRUE
GROUP BY 3 collapse rows into groups (next chapter)
HAVING 4 drop groups (next chapter)
ORDER BY 6 sort the remaining rows
LIMIT / OFFSET 7 cut the sorted rows

Two consequences matter now. WHERE runs before SELECT, so you cannot filter on a column alias you defined in SELECT: SELECT total_cents / 100 AS euros FROM orders WHERE euros > 50 fails, and you repeat the expression or use a subquery. And ORDER BY runs after SELECT, so it can use the alias: ORDER BY euros DESC is fine.

LIMIT without ORDER BY is a trap in the same family as unordered results. SELECT * FROM orders LIMIT 10 returns ten rows, but the executor decides which, and the answer changes between runs. LIMIT is only meaningful after a total order, and a total order needs a tie-breaker: ORDER BY created_at DESC, id DESC, because two orders can share a timestamp and then the page boundary is undefined. Pagination with OFFSET 100000 works but reads and discards 100 000 rows every time; the indexes chapter replaces it with keyset pagination.

DISTINCT turns a bag back into a set for the output columns. It is also a smell: when a query needs DISTINCT to be correct, the usual reason is that a join below it produced duplicates, and the better fix is the join. The last section of this chapter shows why.

The join family

A join combines two relations into one whose tuples pair a row from each side. There are five kinds you will use, and they differ in what happens to rows that do not find a partner.

Cross join pairs every left row with every right row. FROM customers, products with no WHERE is 500 000 × 50 000 = 25 billion rows. Nobody wants it on purpose; everybody produces it by accident when they forget an ON clause or write one that is always true.

Inner join keeps only the pairs where the ON predicate is TRUE. orders JOIN customers ON orders.customer_id = customers.id gives one row per order, because every order has exactly one customer (the foreign key promises it). An order whose customer_id was NULL would vanish, because NULL = anything is UNKNOWN.

Left outer join keeps every left row. Where no right row matches, the right columns are NULL. customers LEFT JOIN orders ON ... gives one row per order plus one row per customer with no orders, the latter with NULL in every orders column. The row count is at least the left row count, and more if the right side is the many side. Right join is the mirror; write it as a left join with the tables swapped, because nobody reads right joins fluently.

Full outer join keeps every row from both sides. Rows with no partner are padded with NULLs. It is the tool for reconciliation: orders FULL JOIN payments ON payments.order_id = orders.id shows orders without a payment and payments without an order in one result.

Semi-join and anti-join are the two that SQL has no keyword for. A semi-join returns each left row at most once if any right row matches: WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). An anti-join returns each left row if no right row matches: WHERE NOT EXISTS (...). The planner has dedicated Hash Semi Join and Hash Anti Join operators for both, and EXPLAIN names them. Use them whenever the question is “which customers have ordered?” rather than “which orders?”; an inner join would return one row per order and force a DISTINCT to clean up.

Two syntax details. USING (id) is a shorthand for ON a.id = b.id that also merges the two columns into one in the output; it reads well but breaks when the columns are named differently, which they are for every foreign key in the shop (customer_id against id). And the ON clause of an outer join is not the same as a WHERE on the same condition. customers LEFT JOIN orders ON orders.customer_id = customers.id AND orders.status = 'paid' keeps every customer and attaches only their paid orders. Move orders.status = 'paid' into WHERE and the customers with no paid orders disappear, because their orders.status is NULL and NULL = 'paid' is UNKNOWN. The left join has silently become an inner join. This is the most common outer-join bug and the lab makes you commit it.

How the engine runs a join

You do not need the planner chapter to read a join, but one fact about execution helps you predict cost. Postgres has three join algorithms. A nested loop takes each left row and looks up matches on the right; it is fast when the right side has an index on the join column and the left side is small. A hash join builds a hash table from the smaller side and probes it with the larger; it is the default for big joins with equality predicates and no useful index. A merge join sorts both sides on the join key and walks them together; it wins when the inputs are already sorted.

After schema.sql the shop has no indexes beyond primary keys and the two unique constraints. That means every join on a foreign key column is a hash join over a sequential scan, and WHERE customer_id = 42 is a sequential scan of two million rows that takes 100 to 300 milliseconds on a laptop. Every query in the lab is written to stay under a few seconds without indexes. When one feels slow, run it with EXPLAIN (ANALYZE, BUFFERS) and look for Seq Scan on a big table; the indexes chapter is where you fix it.

Reading a result that is wrong

The last skill is the one the Why describes. A join between a one side and a many side produces one row per many-side row. Every column from the one side is repeated. Any aggregate over a one-side column is multiplied by the number of many-side matches. This is called fan-out, and it does not error, warn, or look wrong in the first ten rows.

SELECT sum(o.total_cents) FROM orders o JOIN order_items oi ON oi.order_id = o.id returns a number roughly three times the true revenue, because the shop has about three items per order. Join payments in as well and the factor multiplies again. The ranking of countries may even be right, which is how it reaches the board deck.

There are three correct shapes. Aggregate the many side first, in a subquery or CTE, so that it is one row per order before you join it. Sum a column that lives on the many side, such as oi.qty * oi.unit_price_cents, which is the revenue per line and adds up correctly. Or use a semi-join when you only need to know that a match exists. What does not work is DISTINCT, because two different orders can have the same total_cents and DISTINCT on the sum’s input would merge them.

The habit that catches fan-out is to know the expected row count before you run the query and check it after. Joining orders to customers should return exactly count(*) FROM orders. Joining orders to order_items should return exactly count(*) FROM order_items. If the count is different, a row has been dropped (an inner join on a NULL or a missing partner) or repeated (fan-out). Every query in the lab tells you the count to expect.

LAB Twenty queries, from one table to a four-way join ~45 MIN
YOU NEEDDocker Desktop or Docker Engine with Composethe ATLAS repo cloned; labs/databases started with `docker compose up -d` and loaded with `docker compose exec -T db psql -U atlas -d shop -f /shop/load.sql` (add `-v scale=0.1` on a laptop under 8 GB; divide the counts below by 10)about 25 seconds for the loader at scale 1, 3 seconds at 0.1

Open psql against the shop and turn timing on. Every query below states the row count or the shape you should see. Check it before you read the explanation; the point is to predict.

cd labs/databases && docker compose exec db psql -U atlas shop
\timing on
\x auto

1. One table. Relations have a size; learn the shop’s.

SELECT count(*) FROM customers;
SELECT count(*) FROM orders;
SELECT count(*) FROM order_items;
500000, 2000000 and 5999378 at scale 1 (50000, 200000 and 599833 at 0.1). Each count is a sequential scan: around 50 ms for customers and 200 to 400 ms for order_items on a laptop, because Postgres has no row count cached and has to visit every page. Remember the three numbers; every join below is checked against them.

2. Projection and selection.

SELECT id, name, country FROM customers WHERE country = 'NG' ORDER BY created_at DESC, id DESC LIMIT 5;
SELECT id, status, total_cents / 100.0 AS euros FROM orders WHERE total_cents > 50000 ORDER BY euros DESC LIMIT 5;
Five Nigerian customers, newest first; then the five largest orders. The second query uses the alias euros in ORDER BY but could not have used it in WHERE. Try WHERE euros > 500 and read the error: column "euros" does not exist, because WHERE is evaluated before SELECT.

3. LIMIT without ORDER BY.

SELECT id FROM orders LIMIT 3;
UPDATE orders SET status = status WHERE id = (SELECT min(id) FROM orders);
SELECT id FROM orders LIMIT 3;
The first result probably starts with the lowest ids in load order. After the no-op UPDATE, which writes a new row version at the end of the heap, the same query may no longer return the same ids: the first row moved. Physical order is not an order. If you see the same ids both times, the new version landed on the same page; run the update on a few more rows and it will not.

4. Three-valued logic.

SELECT count(*) FROM orders WHERE shipped_at IS NULL;
SELECT count(*) FROM orders WHERE shipped_at = NULL;
SELECT count(*) FROM orders WHERE status NOT IN ('shipped', NULL);
SELECT count(*) FROM orders WHERE shipped_at IS DISTINCT FROM NULL;
299 366 (the 15% of orders that are not shipped; 30 055 at scale 0.1); then 0; then 0; then 1 700 634 (169 945). The second and third are not errors. = NULL is UNKNOWN for every row; NOT IN with a NULL in the list is UNKNOWN for every row. The fourth is the same as IS NOT NULL written with the operator you would use between two columns.

5. NULLs in ORDER BY.

SELECT id, shipped_at FROM orders ORDER BY shipped_at DESC LIMIT 3;
SELECT id, shipped_at FROM orders ORDER BY shipped_at DESC NULLS LAST LIMIT 3;
The first returns three unshipped orders with NULL shipped_at: Postgres sorts NULL as larger than any value, so DESC puts it first. The second returns the three most recently shipped orders. A “latest shipped” report that forgets NULLS LAST shows blanks at the top.

6. Inner join, one-to-one direction. Orders to customers: each order has one customer, so the count must not change.

SELECT count(*) FROM orders o JOIN customers c ON c.id = o.customer_id;
2000000, the same as step 1. If it were less, some order had a customer_id with no matching customer or a NULL; the foreign key forbids the first and the loader does not produce the second. The plan (prefix the query with EXPLAIN) is a Hash Join: Postgres builds a hash table of 500 000 customers and probes it with two million orders.

7. Inner join, one-to-many direction. Orders to items: the count becomes the many side.

SELECT count(*) FROM orders o JOIN order_items oi ON oi.order_id = o.id;
5999378, the order_items count from step 1. The orders rows are repeated once per item. This is the fan-out you will misuse in step 17; here it is harmless because you are counting pairs and know it.

8. Left join and the customers with no orders.

SELECT count(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;
SELECT count(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
The first is 2 000 000 plus the number of customers with no orders; the second is that number on its own: 27 862 at scale 1 (2 771 at 0.1), so the first is 2 027 862. The WHERE o.id IS NULL idiom works because the padded right side is NULL in every column including the primary key, which can never be NULL on a real match.

9. The outer join that became inner.

SELECT count(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'cancelled';
SELECT count(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.status = 'cancelled';
The first count is 540 929 (54 158 at 0.1), at least 500 000: every customer appears, with their cancelled orders attached or with NULLs. The second is far smaller, 139 291 (14 029), the number of cancelled orders: the WHERE dropped every customer whose padded o.status was NULL. Same tables, same condition, different clause, different question.

10. Semi-join with EXISTS.

SELECT count(*) FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
EXPLAIN SELECT count(*) FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
The number of customers with at least one order, which added to step 8’s second count gives 500 000. The plan says Hash Semi Join (or Hash Join with a HashAggregate on the inner side at some scales): Postgres knows it needs each customer at most once and stops probing after the first match.

11. Anti-join, the right way.

SELECT count(*) FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
The same number as step 8’s second query, from a hash anti-join (EXPLAIN on Postgres 17 prints Parallel Hash Right Anti Join: it hashes the customers and probes with the orders, keeping the customers no order matched). Unlike NOT IN, NOT EXISTS cannot be poisoned by a NULL in the subquery: it asks whether any row exists, and a row with a NULL customer_id does not match any customer.

12. The NOT IN trap, made real. The shop declares orders.customer_id NOT NULL, which is the right design, so you cannot insert the poison row. Add the NULL to the subquery instead; it is exactly what a nullable foreign key, or a LEFT JOIN feeding the subquery, would hand you in production.

SELECT count(*) FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);

SELECT count(*) FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders UNION ALL SELECT NULL);

SELECT count(*) FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
The first and third counts match step 11: the customers who never ordered. The second is 0. One NULL among two million values switched off the whole predicate, with no error and no warning. NOT EXISTS has no such failure mode, because it asks whether a matching row exists and a NULL matches nothing. Use NOT EXISTS for anti-joins, always, and the question of which columns are nullable stops mattering.

13. Full outer join for reconciliation.

SELECT count(*) FILTER (WHERE p.id IS NULL)  AS orders_without_payment,
       count(*) FILTER (WHERE o.id IS NULL)  AS payments_without_order
FROM orders o FULL JOIN payments p ON p.order_id = o.id;
The second number is 0, because the foreign key makes an orphan payment impossible. The first is also 0: load.sql writes exactly one payment per order. The query shape is the one you want for any two systems that should agree; FILTER is a Postgres aggregate clause you will use often in the next chapter.

14. Three tables. Items for one customer’s orders, with product names.

SELECT o.id AS order_id, o.created_at::date AS day, p.name, oi.qty, oi.unit_price_cents
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.customer_id = 42
ORDER BY o.created_at, oi.id;
One row per line item for customer 42: 4 rows at scale 1, 7 at scale 0.1. Before running it, predict the count: it is SELECT count(*) FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE customer_id = 42). Check. The join to products is many-to-one and cannot change the count; the join to order_items set it.

15. Four tables. Add the customer.

SELECT c.name, c.country, o.id AS order_id, o.status, p.name AS product, oi.qty
FROM customers c
JOIN orders o       ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p     ON p.id = oi.product_id
WHERE c.id = 42
ORDER BY o.created_at, oi.id;
The same row count as step 14, with the customer’s name repeated on every row. That repetition is correct and harmless in a listing. It is the thing that goes wrong the moment you put a sum() over an order-level column on top of it.

16. Cross join by accident. Do not run this without the LIMIT.

SELECT count(*) FROM (SELECT * FROM customers c, products p LIMIT 1000000) x;
1000000 in well under a second, which hides the problem: the full cross product is 25 billion rows. Remove the LIMIT and Postgres will run for hours. The comma syntax is a cross join; a missing ON clause in explicit JOIN syntax is a syntax error, which is one reason to prefer it.

17. Fan-out, the wrong number. The query from the Why.

SELECT sum(o.total_cents) / 100 AS euros_true FROM orders o;
SELECT sum(o.total_cents) / 100 AS euros_wrong
FROM orders o JOIN order_items oi ON oi.order_id = o.id;
The second figure is about 3.7 times the first (331 041 450 against 1 214 406 743 at scale 1), because every order is repeated once per item. Nothing warns you. The ratio is above the plain 3 items per order because orders with more lines also have larger totals, so they are repeated more and weigh more; (SELECT count(*) FROM order_items)::numeric / (SELECT count(*) FROM orders) is the unweighted version.

18. Fan-out, fixed three ways.

-- a: aggregate the many side first
SELECT sum(o.total_cents) / 100 AS euros
FROM orders o
JOIN (SELECT order_id, count(*) AS lines FROM order_items GROUP BY order_id) li ON li.order_id = o.id;

-- b: sum a column that lives on the many side
SELECT sum(oi.qty * oi.unit_price_cents) / 100 AS euros
FROM orders o JOIN order_items oi ON oi.order_id = o.id;

-- c: semi-join when you only need existence
SELECT sum(o.total_cents) / 100 AS euros
FROM orders o WHERE EXISTS (SELECT 1 FROM order_items oi WHERE oi.order_id = o.id);
All three agree with step 17’s euros_true. Every order has at least one item, so a and c exclude nothing, and b agrees because load.sql sets orders.total_cents to the sum of its lines. In a real system b drifting from a is the denormalisation drift that the modelling chapter is about.

19. Fan-out squared. Two many-sides at once.

SELECT count(*)
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN payments p    ON p.order_id = o.id
WHERE o.id < 1000;
2985 at scale 1 (3061 at 0.1), the same as SELECT count(*) FROM order_items WHERE order_id < 1000, because load.sql writes exactly one payment per order.

Give some orders a second payment (a failed attempt before the capture) inside a transaction and run it again:

BEGIN;
INSERT INTO payments (order_id, provider, status, amount_cents)
SELECT id, 'card', 'failed', total_cents FROM orders WHERE id < 1000 AND id % 10 = 0;
-- re-run the count above
ROLLBACK;
Now the join count is higher than the item count: every item of those orders appears twice. The difference is the number of item rows duplicated by the second one-to-many edge. Two many-sides in one FROM is the pattern to refuse in code review unless each one is pre-aggregated.

20. The row-count check as a habit. Write it as a single query you can paste under any join.

WITH joined AS (
  SELECT o.id
  FROM orders o
  JOIN customers c ON c.id = o.customer_id
  WHERE c.country = 'DE'
)
SELECT (SELECT count(*) FROM joined)                                       AS joined_rows,
       (SELECT count(*) FROM orders o JOIN customers c ON c.id = o.customer_id
         WHERE c.country = 'DE')                                            AS expected_rows,
       (SELECT count(DISTINCT id) FROM joined)                              AS distinct_orders;
All three numbers are equal, which proves the join neither dropped nor repeated orders. When joined_rows exceeds distinct_orders, you have fan-out; when expected_rows exceeds joined_rows, you have dropped rows. Put this shape around every join you ship for the first month and the habit will outlast the query.
Change step 14’s last join to JOIN products p ON p.id = oi.order_id: a wrong join key that happens to be type-compatible. It runs without error and returns no rows: order ids run to two million and product ids stop at 50 000 (5 000 at scale 0.1), and customer 42’s orders all have ids far above that. A customer whose orders have low ids would get rows back, with nonsense product names on them. Nothing in SQL knows which bigint is a foreign key to which table; only you and the row-count check do. Then run step 15 with count(*) and the row-count check from step 20 wrapped around it: the mismatch between joined_rows and expected_rows is how you would have caught this in review.
DECIDE

A revenue-by-country report joins customers to orders to order_items to payments and sums orders.total_cents. It is about 3x too high. The dashboard team wants the fix today and proposes dividing the result by the average items per order. What do you ship?

READING
  1. PAPER
    A Relational Model of Data for Large Shared Data Banks E. F. Codd, 1970

    The ten pages that started the field. Section 1 is readable by anyone and gives you relations, keys and the argument for data independence; section 2 defines the operations that became joins. Skip the normal-form discussion until the next chapter. Read: section 1 in full; section 2.1 for the join operations.

  2. POST
    The Three-Valued Logic of SQL Markus Winand, 2015

    Truth tables for AND, OR and NOT with UNKNOWN, and the cases where it bites: NOT IN, CHECK constraints, and DISTINCT. Twenty minutes that save a production incident.

  3. BOOK
    SQL Performance Explained, chapter 1: Anatomy of an SQL Index Markus Winand, 2012

    The key reading for this chapter per the course plan: what a lookup costs and why a WHERE on a key is different from a WHERE on any other column. The free online edition is complete. Stop at the end of chapter 1; the indexes chapter picks up chapters 2 and 3. Read: chapter 1 (Anatomy of an SQL Index) and the first section of chapter 2.

  4. DOC
    PostgreSQL 17: Table Expressions (joins, subqueries, LATERAL)

    The authoritative definition of every join type with small worked examples, plus LATERAL, which you will need for top-N per group. Read 7.2.1 now; the rest when you need it.

  5. DOC
    PostgreSQL 17: SELECT

    The reference page for the statement, including the sentence about unordered results and the NULLS FIRST/LAST defaults. Skim the synopsis; read the ORDER BY and LIMIT sections properly.

  6. POST
    A Visual Explanation of SQL Joins Jeff Atwood, 2007

    The Venn-diagram picture of inner, left, right, full and anti joins. Useful as a memory aid; be aware that Venn diagrams do not show fan-out, which is why this chapter does not rely on them.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Modelling: keys, normalisation, and when to denormalise →