DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·56

SQL from SELECT to Window Functions

SQL as a declarative language: the logical processing order, filtering, sorting and paging, joins of every kind (including semi- and anti-joins), grouping and HAVING, aggregates with FILTER and grouping sets, subqueries and CTEs, set operations, CASE, window functions with frames, recursive CTEs, LATERAL joins, upserts and MERGE, RETURNING, generated columns, JSON/jsonb and JSON_TABLE, arrays, and full-text search. PostgreSQL syntax first, with MySQL, SQLite, SQL Server and Oracle differences noted.

34 topics · ~33 min read · 32-question quiz
Updated Suggest a correction

Start here: asking questions in SQL

The shape of a query

A SELECT describes the rows you want; the database works out how to get them. Its clauses are written in one order but evaluated in another, and that evaluation order explains most SQL surprises:

Written Evaluated What it does
SELECT columns 5 Choose and compute output columns (and window functions)
FROM / JOIN 1 Pick tables and combine them into one wide set of rows
WHERE 2 Keep rows matching a condition (before grouping)
GROUP BY 3 Collapse rows into groups
HAVING 4 Keep groups matching a condition (after grouping)
ORDER BY 6 Sort
LIMIT / OFFSET 7 Take a slice

So WHERE can't use an alias defined in SELECT (it runs first), and WHERE can't filter on sum(…) (groups don't exist yet; that's HAVING's job).

Filtering, sorting, limiting

SQL
SELECT name, price_paise FROM dish
WHERE category IN ('breakfast','drinks') AND price_paise < 6000
ORDER BY price_paise DESC LIMIT 3;
Text
     name      | price_paise
---------------+-------------
 Idli          |        5000
 Vada          |        4000
 Filter coffee |        3000

Without ORDER BY, rows come back in whatever order is convenient for the database, which can change between runs; LIMIT without ORDER BY means "any three rows".

Joining tables

A join combines rows from two tables where a condition holds, usually a key matching a foreign key. An inner join (JOIN) keeps only matched pairs; a left join keeps every row from the left table, filling the right side with NULLs when nothing matches:

SQL
SELECT c.name, count(o.id) AS orders
FROM customer c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name ORDER BY orders DESC, c.name;
Text
 name  | orders
-------+--------
 Asha  |      3
 Meena |      2
 Ravi  |      2
 Kiran |      1
 Zoya  |      0

Zoya has never ordered. With an inner join she would vanish; the left join keeps her, and count(o.id) counts only non-NULL order ids, giving 0. (count(*) would have counted her NULL-filled row as 1.)

Grouping, and the fan-out trap

SQL
SELECT c.city, count(*) AS rows_after_join, count(DISTINCT o.id) AS orders, sum(l.qty * d.price_paise) / 100 AS revenue_rupees
FROM orders o JOIN customer c ON c.id = o.customer_id
              JOIN order_line l ON l.order_id = o.id
              JOIN dish d ON d.id = l.dish_id
WHERE o.status = 'DELIVERED'
GROUP BY c.city HAVING sum(l.qty * d.price_paise) > 30000
ORDER BY revenue_rupees DESC;
Text
   city    | rows_after_join | orders | revenue_rupees
-----------+-----------------+--------+----------------
 Chennai   |               3 |      2 |            600
 Bengaluru |               6 |      3 |            540
 Hyderabad |               2 |      1 |            340

Read it in evaluation order: join four tables into one row per order line, keep delivered orders, group by city, keep cities with more than ₹300 of revenue, compute the outputs, sort. Notice rows_after_join: joining orders to their lines multiplies rows (one per line), so count(*) counts lines, not orders. That's fan-out, and it silently inflates counts and sums whenever you aggregate a value from the "one" side after joining a "many" side; count(DISTINCT o.id) gives the real order count. The lab shows a revenue report inflated 3.3× by exactly this.

Building in steps: CTEs and window functions

SQL
WITH order_total AS (                                   -- a named intermediate result
  SELECT o.id, o.customer_id, o.placed_at, sum(l.qty * d.price_paise) / 100 AS total
  FROM orders o JOIN order_line l ON l.order_id = o.id JOIN dish d ON d.id = l.dish_id
  WHERE o.status <> 'CANCELLED' GROUP BY o.id)
SELECT c.name, t.id AS order_id, t.placed_at::date AS day, t.total,
       sum(t.total) OVER (PARTITION BY t.customer_id ORDER BY t.placed_at) AS running_total,
       rank()       OVER (ORDER BY t.total DESC)                           AS size_rank
FROM order_total t JOIN customer c ON c.id = t.customer_id
ORDER BY c.name, t.placed_at;
Text
 name  | order_id |    day     | total | running_total | size_rank
-------+----------+------------+-------+---------------+-----------
 Asha  |      101 | 2026-10-01 |   240 |           240 |         3
 Asha  |      103 | 2026-10-02 |   130 |           370 |         7
 Asha  |      106 | 2026-10-04 |   170 |           540 |         6
 Kiran |      105 | 2026-10-03 |   340 |           340 |         2
 Meena |      108 | 2026-10-05 |   240 |           240 |         3
 Ravi  |      102 | 2026-10-01 |   240 |           240 |         3
 Ravi  |      107 | 2026-10-04 |   360 |           600 |         1

A CTE (WITH name AS (…)) names a subquery so the main query reads in steps. A window function computes a value for each row from a set of related rows (its window) without collapsing them the way GROUP BY does. PARTITION BY customer_id ORDER BY placed_at makes sum(…) a running total per customer; rank() OVER (ORDER BY total DESC) ranks every order by size, with ties sharing a rank (three orders tie at 3, so the next is 6).

One more pattern you'll write constantly, "the top item in each group":

SQL
SELECT category, name, sold FROM (
  SELECT d.category, d.name, sum(l.qty) AS sold,
         row_number() OVER (PARTITION BY d.category ORDER BY sum(l.qty) DESC, d.name) AS rn
  FROM order_line l JOIN dish d ON d.id = l.dish_id GROUP BY d.category, d.name) x
WHERE rn = 1 ORDER BY category;
Text
 category  |     name      | sold
-----------+---------------+------
 breakfast | Idli          |    5
 drinks    | Filter coffee |    6
 lunch     | Biryani       |    3

How deep to go in SQL

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Write SELECT with filters, sorting, joins and simple aggregates
L2 Use outer joins, GROUP BY/HAVING, subqueries, CTEs and window functions correctly
L3 Explain evaluation order, NULL semantics in joins and aggregates, set operations, recursive CTEs, LATERAL and frames
L4 Diagnose fan-out, vanishing outer joins, NULL traps and slow formulations; rewrite them
L5 Design reporting and analytical queries and the schema support (indexes, materialised views) they need
L6 Set SQL conventions, review practices and performance budgets for a team

Thinking in SQL

A declarative language

SQL describes what result you want, as an expression over relations. The database decides how to compute it. Two consequences:

  • Think in sets, not loops. "For each order, look up its customer" is a join, not a loop with a query inside (the N+1 pattern of Vol. 3 ch. 49). One set-based statement lets the planner choose hash joins, parallel scans and index lookups. A thousand single-row queries can't be optimised together.
  • The text order isn't the execution order. SELECT is written first but evaluated almost last.

Logical processing order

1 FROMJOIN 2 WHERE 3 GROUPBY 4 HAVING 5 windowOVER() 6 SELECTDISTINCT 7 ORDERBY 8 LIMITOFFSET WHERE filters rows before grouping; HAVING filters groups after aggregation. Window functions see the rows that survived WHERE/GROUP BY/HAVING. SELECT aliases exist from step 6: usable in ORDER BY, not in WHERE. This is the LOGICAL order; the physical plan may push filters down, reorder joins, etc.
Logical query processing order. Clauses are evaluated FROM first and SELECT near the end, which explains why a SELECT alias can't be used in WHERE but can in ORDER BY.
SQL
SELECT customer_id, sum(total_cents) AS revenue      -- 6
FROM orders                                           -- 1
WHERE status = 'PAID'                                 -- 2  (can't use 'revenue' here)
GROUP BY customer_id                                  -- 3
HAVING sum(total_cents) > 100000                      -- 4  (PostgreSQL doesn't allow the alias here)
ORDER BY revenue DESC                                 -- 7  (alias OK)
LIMIT 10;                                             -- 8

Querying single tables

SELECT, WHERE, ORDER BY

SQL
SELECT id, status, total_cents / 100.0 AS total, created_at
FROM orders
WHERE status IN ('PAID', 'SHIPPED')
  AND created_at >= '2026-10-01' AND created_at < '2026-11-01'   -- half-open ranges for time
  AND customer_id = $1                                            -- bind parameters, never string concatenation
  AND (coupon_code ILIKE 'SALE%' OR total_cents > 50000)          -- ILIKE: case-insensitive (PostgreSQL)
ORDER BY created_at DESC, id DESC                                 -- unique tie-breaker → deterministic order
LIMIT 50;
  • Predicates: =, <>, <, BETWEEN (inclusive on both ends, so avoid it for timestamps), IN (…), LIKE/ILIKE with % and _, IS [NOT] NULL, IS [NOT] DISTINCT FROM, regular expressions (~ in PostgreSQL), and EXISTS.
  • Sargable predicates ("search-argument-able") can use an index: created_at >= $1. Wrapping the column in a function usually prevents index use: date(created_at) = '2026-10-24' and lower(email) = $1 need an expression index or a rewrite as a range (chapter 60).
  • ORDER BY without a unique key is non-deterministic: rows with equal sort keys can come back in any order, and that order can change between runs. That's especially bad for pagination.
  • Collation decides string order and equality: 'a' < 'B'? Is 'é' = 'e'? Locale collations (ICU) differ from byte order (C). Indexes built under one collation must match the query's. OS libc upgrades that changed collation rules have silently corrupted indexes in the past, which is why ICU collations or the built-in C/PG_C_UTF8/PG_UNICODE_FAST providers are recommended.
  • Paging: LIMIT n OFFSET m (PostgreSQL, MySQL, SQLite), OFFSET m ROWS FETCH NEXT n ROWS ONLY (the SQL standard: PostgreSQL, SQL Server, Oracle 12c+), TOP n (SQL Server). Keyset pagination scales better (Vol. 3 ch. 45):
SQL
-- Keyset (seek) pagination using a row-value comparison
SELECT id, created_at, total_cents FROM orders
WHERE customer_id = $1 AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 50;

CASE and conditional expressions

SQL
SELECT id,
       CASE
         WHEN total_cents >= 100000 THEN 'large'
         WHEN total_cents >= 10000  THEN 'medium'
         ELSE 'small'
       END AS size_band,                                -- searched CASE: the first true WHEN wins
       CASE status WHEN 'PAID' THEN 1 WHEN 'SHIPPED' THEN 2 ELSE 0 END AS status_rank,   -- simple CASE
       COALESCE(coupon_code, '—') AS coupon,            -- first non-null argument
       NULLIF(discount_cents, 0) AS discount_or_null,   -- NULL if equal: avoids division by zero
       GREATEST(shipping_cents, 0) AS shipping          -- LEAST/GREATEST (NULLs are ignored in PostgreSQL)
FROM orders;

SELECT total_cents::numeric / NULLIF(item_count, 0) AS avg_item;   -- divide safely

Combining tables

Joins

A join combines rows from two relations where a condition holds. Every join is logically a filtered Cartesian product:

INNERmatches only LEFTall left + NULLs FULLall of both SEMIEXISTS ANTINOT EXISTS Venn diagrams simplify: joins match rows and can multiply them
Join types. Inner keeps matching pairs; left keeps all left rows with NULLs where unmatched; full keeps both sides; semi- and anti-joins test existence without duplicating rows.
SQL
-- INNER JOIN: only orders with a matching customer
SELECT o.id, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id;

-- LEFT JOIN: every customer, with order counts (zero included)
SELECT c.id, c.email, count(o.id) AS orders          -- count(o.id), NOT count(*): count(*) would count the NULL row as 1
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'PAID'   -- filter in ON keeps unmatched customers
GROUP BY c.id, c.email;
-- Putting "o.status = 'PAID'" in WHERE instead would DISCARD customers with no paid orders (NULL ≠ 'PAID'),
-- silently turning the LEFT JOIN into an inner join. A very common bug.

-- FULL OUTER JOIN: reconcile two sources
SELECT coalesce(a.sku, b.sku) AS sku, a.qty AS warehouse_qty, b.qty AS erp_qty
FROM warehouse_stock a
FULL JOIN erp_stock b ON b.sku = a.sku
WHERE a.qty IS DISTINCT FROM b.qty;

-- CROSS JOIN: every combination (calendars, test matrices)
SELECT d::date, s.name FROM generate_series('2026-10-01'::date, '2026-10-07', '1 day') d CROSS JOIN stores s;

-- Self-join: employees with their managers
SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON m.id = e.manager_id;

-- SEMI-JOIN: customers who have at least one paid order (no duplicates, no order columns)
SELECT c.* FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'PAID');

-- ANTI-JOIN: customers with NO orders (NULL-safe, unlike NOT IN)
SELECT c.* FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
  • Row multiplication: joining one-to-many multiplies parent rows. Aggregating after joining two independent one-to-many relations double counts: orders ⋈ lines ⋈ payments gives lines × payments rows per order, so sum(payments.amount) is inflated. Aggregate each child separately (subqueries or CTEs), then join.
  • RIGHT JOIN is a LEFT JOIN with the tables swapped. Prefer LEFT for readability.
  • USING (customer_id) and NATURAL JOIN save typing. Avoid NATURAL JOIN: it silently changes meaning when someone adds a column with a shared name.
  • MySQL has no FULL OUTER JOIN; emulate it with LEFT JOIN … UNION … RIGHT JOIN.

Subqueries

SQL
-- Scalar subquery (must return at most one row and one column)
SELECT id, total_cents,
       total_cents - (SELECT avg(total_cents) FROM orders) AS vs_avg
FROM orders;

-- Correlated subquery: evaluated per outer row logically (the planner often rewrites it as a join)
SELECT c.id,
       (SELECT max(created_at) FROM orders o WHERE o.customer_id = c.id) AS last_order_at
FROM customers c;

-- Derived table (subquery in FROM)
SELECT band, count(*) FROM (
    SELECT CASE WHEN total_cents >= 10000 THEN 'big' ELSE 'small' END AS band FROM orders
) t GROUP BY band;

-- IN / ANY / ALL
SELECT * FROM products WHERE category_id IN (SELECT id FROM categories WHERE parent_id = 7);
SELECT * FROM orders WHERE total_cents > ALL (SELECT total_cents FROM orders WHERE customer_id = 42);
SELECT * FROM orders WHERE id = ANY($1::uuid[]);       -- PostgreSQL: pass an array parameter instead of building IN lists

Common table expressions

CTEs (WITH) name intermediate results, making complex queries readable and composable:

SQL
WITH paid AS (
    SELECT customer_id, sum(total_cents) AS revenue, count(*) AS orders
    FROM orders WHERE status = 'PAID' AND created_at >= now() - interval '90 days'
    GROUP BY customer_id
),
ranked AS (
    SELECT p.*, ntile(10) OVER (ORDER BY revenue DESC) AS decile FROM paid p
)
SELECT c.email, r.revenue, r.orders
FROM ranked r JOIN customers c ON c.id = r.customer_id
WHERE r.decile = 1
ORDER BY r.revenue DESC;
  • Since PostgreSQL 12, non-recursive CTEs referenced once are inlined (optimised together with the outer query). Use MATERIALIZED to force a separate evaluation (an "optimisation fence", sometimes useful) or NOT MATERIALIZED to force inlining. Before PostgreSQL 12 they were always fences, which surprised many people.
  • Data-modifying CTEs (PostgreSQL) chain writes atomically in one statement:
SQL
WITH moved AS (
    DELETE FROM orders_pending WHERE created_at < now() - interval '7 days' RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;

Set operations

SQL
SELECT email FROM newsletter_subscribers
UNION                       -- distinct union (sorts or hashes to remove duplicates)
SELECT email FROM customers;

SELECT sku FROM catalog
EXCEPT                      -- in the first, not the second (Oracle before 21c: MINUS)
SELECT sku FROM discontinued;

SELECT customer_id FROM orders WHERE created_at >= '2026-01-01'
INTERSECT                   -- in both
SELECT customer_id FROM support_tickets;
  • UNION ALL keeps duplicates and avoids the deduplication cost. Use it whenever duplicates are impossible or wanted.
  • Columns are matched by position, not name, and types must be compatible.
  • Set operations treat NULLs as equal (like DISTINCT).

Aggregation

GROUP BY, HAVING and aggregates

SQL
SELECT date_trunc('day', created_at) AS day,
       count(*)                                         AS orders,
       count(DISTINCT customer_id)                      AS customers,
       sum(total_cents)                                 AS revenue,
       avg(total_cents)::bigint                         AS avg_order,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY total_cents) AS median,     -- ordered-set aggregate
       count(*) FILTER (WHERE status = 'CANCELLED')     AS cancelled,          -- conditional aggregate
       string_agg(DISTINCT currency, ',' ORDER BY currency) AS currencies,
       array_agg(id ORDER BY created_at) FILTER (WHERE total_cents > 100000) AS big_orders,
       bool_or(coupon_code IS NOT NULL)                 AS any_coupon
FROM orders
WHERE created_at >= now() - interval '30 days'
GROUP BY 1                                              -- by position: allowed, but names read better
HAVING count(*) > 10
ORDER BY day;
  • Every selected column must be grouped or aggregated. PostgreSQL allows ungrouped columns that are functionally dependent on a grouped primary key (GROUP BY c.id lets you select c.email). Old MySQL modes allowed any ungrouped column and returned an arbitrary value. ONLY_FULL_GROUP_BY (the default since 5.7) fixed that.
  • FILTER (WHERE …) (PostgreSQL, SQLite) is cleaner than sum(CASE WHEN … THEN 1 ELSE 0 END), which is the portable equivalent.
  • Grouping sets compute several groupings in one pass:
SQL
SELECT country, channel, sum(total_cents)
FROM orders JOIN customers c ON c.id = orders.customer_id
GROUP BY ROLLUP (country, channel);        -- (country, channel), (country), () grand total
-- CUBE (a, b) → all combinations; GROUPING SETS ((a), (b), ()) → exactly those
-- grouping(col) tells you whether a NULL means "subtotal" or a real NULL

Window functions

Window functions compute a value for each row from a set of related rows (its window) without collapsing rows the way GROUP BY does. They're one of the most powerful SQL features, and supported by PostgreSQL, MySQL 8+, SQLite 3.25+, SQL Server and Oracle.

Text
function(args) OVER (
    PARTITION BY …     -- split rows into independent groups (like GROUP BY, but rows are kept)
    ORDER BY …         -- order within each partition
    ROWS | RANGE | GROUPS BETWEEN … AND …   -- the frame: which rows relative to the current one
)
SQL
SELECT id, customer_id, created_at, total_cents,
  row_number() OVER w                                   AS nth_order,        -- 1, 2, 3, … per customer
  rank()       OVER (PARTITION BY customer_id ORDER BY total_cents DESC) AS size_rank,   -- ties share a rank, gaps after
  dense_rank() OVER (PARTITION BY customer_id ORDER BY total_cents DESC) AS dense,       -- no gaps
  lag(created_at)  OVER w                               AS prev_order_at,    -- previous row's value
  created_at - lag(created_at) OVER w                   AS gap_since_prev,
  lead(total_cents) OVER w                              AS next_total,
  sum(total_cents) OVER (PARTITION BY customer_id ORDER BY created_at
                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
  avg(total_cents) OVER (PARTITION BY customer_id ORDER BY created_at
                         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)   AS moving_avg_3,
  total_cents::numeric / sum(total_cents) OVER (PARTITION BY customer_id) AS share_of_customer,
  first_value(id) OVER w                                AS first_order_id,
  ntile(4) OVER (ORDER BY total_cents)                  AS quartile
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY created_at);   -- a named window, reused
PARTITION BY customer_id ORDER BY created_at · ROWS UNBOUNDED PRECEDING → CURRENT ROW cust 7 · Oct 01 · 100running 100 cust 7 · Oct 03 · 50running 150 cust 7 · Oct 09 · 200 ← current rowrunning 350 cust 7 · Oct 20 · 25running 375 frame forcurrent row cust 9 · Oct 02 · 80running 80 new partition GROUP BY would collapse each customer into one row; OVER keeps all rows and adds a column
A window function keeps every row. Rows are partitioned by customer and ordered by time; for the current row the frame (here, unbounded preceding to current row) defines which rows feed the aggregate, giving a running total.

Frames need care:

  • With ORDER BY but no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes peers (rows with equal sort values). A running total over equal timestamps then jumps by the whole peer group. Use ROWS for row-by-row frames.
  • last_value() with the default frame returns the current row (the frame ends at the current row). Use ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
  • RANGE BETWEEN interval '7 days' PRECEDING AND CURRENT ROW gives time-based moving windows (PostgreSQL 11+).

Classic window-function solutions:

SQL
-- Top-N per group: the 3 most recent orders per customer
SELECT * FROM (
    SELECT o.*, row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
    FROM orders o
) t WHERE rn <= 3;            -- window results can't be filtered in the same WHERE: wrap in a subquery
-- (an alternative is a LATERAL join with LIMIT 3: often faster with the right index, see below)

-- Deduplicate: keep the newest row per email
DELETE FROM signups s USING (
    SELECT id, row_number() OVER (PARTITION BY lower(email) ORDER BY created_at DESC) AS rn FROM signups
) d WHERE s.id = d.id AND d.rn > 1;

-- Gaps and islands: consecutive days with activity per user (streaks)
SELECT user_id, min(day) AS streak_start, max(day) AS streak_end, count(*) AS days
FROM (
    SELECT user_id, day, day - (row_number() OVER (PARTITION BY user_id ORDER BY day))::int AS grp
    FROM (SELECT DISTINCT user_id, created_at::date AS day FROM events) e
) t
GROUP BY user_id, grp;

-- Period-over-period change
SELECT month, revenue,
       revenue - lag(revenue) OVER (ORDER BY month) AS delta,
       round(100.0 * (revenue / nullif(lag(revenue) OVER (ORDER BY month), 0) - 1), 1) AS pct
FROM monthly_revenue;

The same idea exists in dataframes: pandas groupby().cumsum()/rolling(), Polars over(), and Spark SQL windows.

Advanced SQL

Recursive CTEs

A recursive CTE runs a query repeatedly, feeding each iteration's output into the next, until no new rows appear. It's the way to traverse trees and graphs stored as adjacency lists:

SQL
-- Category tree: all descendants of category 7, with depth and path
WITH RECURSIVE tree AS (
    SELECT id, parent_id, name, 1 AS depth, ARRAY[id] AS path          -- anchor member
    FROM categories WHERE id = 7
  UNION ALL
    SELECT c.id, c.parent_id, c.name, t.depth + 1, t.path || c.id      -- recursive member
    FROM categories c
    JOIN tree t ON c.parent_id = t.id
    WHERE NOT c.id = ANY(t.path)                                        -- cycle guard (or the CYCLE clause, PG 14+)
      AND t.depth < 20                                                  -- depth guard
)
SELECT repeat('  ', depth - 1) || name AS indented FROM tree ORDER BY path;

-- Org chart upwards: the management chain of employee 42
WITH RECURSIVE chain AS (
    SELECT id, manager_id, name FROM employees WHERE id = 42
  UNION ALL
    SELECT e.id, e.manager_id, e.name FROM employees e JOIN chain ON e.id = chain.manager_id
)
SELECT * FROM chain;

-- Generate series without a helper function (portable)
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100) SELECT i FROM n;

PostgreSQL 14+ adds SEARCH DEPTH FIRST BY … / BREADTH FIRST and CYCLE id SET is_cycle USING path clauses. Alternatives for trees: the ltree extension (materialised paths with indexed ancestor queries), nested sets, and closure tables (an explicit ancestor/descendant table, which makes reads fast and writes costly). For heavy graph traversal, consider a graph database (chapter 62).

LATERAL joins

A LATERAL subquery in FROM can reference columns of preceding FROM items. It's a "for each row, run this subquery" that the planner can still optimise. SQL Server and Oracle call it CROSS APPLY/OUTER APPLY:

SQL
-- Top-3 most recent orders per customer: with an index on orders(customer_id, created_at DESC),
-- this does 3 index-ordered reads per customer instead of numbering every order
SELECT c.id, c.email, o.id AS order_id, o.created_at
FROM customers c
CROSS JOIN LATERAL (
    SELECT id, created_at FROM orders
    WHERE customer_id = c.id
    ORDER BY created_at DESC
    LIMIT 3
) o;

-- LEFT JOIN LATERAL … ON true keeps customers with no orders
SELECT c.id, latest.created_at
FROM customers c
LEFT JOIN LATERAL (SELECT created_at FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 1) latest ON true;

-- Unnesting set-returning functions per row
SELECT o.id, item->>'sku' AS sku, (item->>'qty')::int AS qty
FROM orders_json o, LATERAL jsonb_array_elements(o.doc->'lines') AS item;   -- comma + LATERAL = cross join

Writing data: INSERT, UPDATE, DELETE, upserts and RETURNING

SQL
-- Multi-row insert with RETURNING (generated keys come back in the same round trip)
INSERT INTO order_lines (order_id, line_no, sku, qty, unit_cents)
VALUES ($1, 1, 'A1', 2, 1999), ($1, 2, 'B7', 1, 4999)
RETURNING line_no, sku;

-- Upsert: insert or update on a unique-key conflict (atomic, race-free)
INSERT INTO inventory (sku, qty) VALUES ($1, $2)
ON CONFLICT (sku) DO UPDATE SET qty = inventory.qty + EXCLUDED.qty, updated_at = now()
RETURNING qty;
-- ON CONFLICT … DO NOTHING: idempotent inserts (Vol. 3 ch. 51's inbox pattern)
-- MySQL: INSERT … ON DUPLICATE KEY UPDATE · SQLite: ON CONFLICT … DO UPDATE (3.24+)

-- UPDATE with a join (PostgreSQL FROM; SQL Server UPDATE … FROM; MySQL UPDATE t JOIN …)
UPDATE orders o SET status = 'EXPIRED'
FROM customers c
WHERE c.id = o.customer_id AND c.country_code = 'DE' AND o.status = 'PENDING' AND o.created_at < now() - interval '7 days';

-- PostgreSQL 18: RETURNING old and new values
UPDATE accounts SET balance_cents = balance_cents - 500 WHERE id = $1
RETURNING old.balance_cents AS before, new.balance_cents AS after;

-- MERGE (SQL standard; PostgreSQL 15+, RETURNING in 17; SQL Server; Oracle)
MERGE INTO inventory i
USING (VALUES ('A1', 5), ('Z9', 2)) AS s(sku, delta) ON i.sku = s.sku
WHEN MATCHED AND i.qty + s.delta <= 0 THEN DELETE
WHEN MATCHED THEN UPDATE SET qty = i.qty + s.delta
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.delta);

INSERT … ON CONFLICT is safer than MERGE for concurrent upserts in PostgreSQL. MERGE can still fail with a unique violation if a concurrent transaction inserts the same key between its check and its insert. In SQL Server, MERGE has a long list of concurrency caveats too (use HOLDLOCK).

Generated columns

A generated column is computed from other columns of the same row:

SQL
CREATE TABLE order_lines (
    qty        int    NOT NULL,
    unit_cents bigint NOT NULL,
    line_cents bigint GENERATED ALWAYS AS (qty * unit_cents) STORED,        -- computed on write, stored, indexable
    sku_upper  text   GENERATED ALWAYS AS (upper(sku)) VIRTUAL,            -- PostgreSQL 18: computed on read
    sku        text   NOT NULL
);
  • STORED: computed on insert and update and stored on disk. It can be indexed. PostgreSQL has supported it since 12.
  • VIRTUAL: computed when read, using no storage. It's PostgreSQL 18's default kind, though virtual columns can't yet be indexed. MySQL has had both (VIRTUAL is the default there, and InnoDB can index virtual columns through secondary indexes), and SQL Server has computed columns (PERSISTED optional).
  • Expressions must be immutable (no now(), no other tables).
  • An alternative for search is an expression index (CREATE INDEX ON t (upper(sku))), which needs no column at all.

JSON and jsonb

PostgreSQL's jsonb stores JSON in a decomposed binary format: keys are deduplicated and sorted, and it's fast to query and index (json keeps the original text, whitespace and duplicate keys, and must be re-parsed). It gives you document storage inside a relational database:

SQL
CREATE TABLE events (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    type    text  NOT NULL,
    payload jsonb NOT NULL,
    at      timestamptz NOT NULL DEFAULT now()
);

-- Operators
SELECT payload->'customer'->>'email'          AS email,       -- -> returns jsonb, ->> returns text
       payload #>> '{shipping,address,city}'  AS city,        -- path extraction
       (payload->>'total_cents')::bigint      AS total
FROM events
WHERE payload @> '{"status": "PAID"}'                         -- containment (GIN-indexable)
  AND payload ? 'coupon'                                      -- key exists
  AND jsonb_path_exists(payload, '$.lines[*] ? (@.qty > 10)'); -- SQL/JSON path (PG 12+)

-- Indexes
CREATE INDEX events_payload_gin ON events USING gin (payload jsonb_path_ops);   -- for @> containment queries
CREATE INDEX events_email ON events ((payload->'customer'->>'email'));           -- expression index for one key

-- Modifying
UPDATE events SET payload = jsonb_set(payload, '{status}', '"REFUNDED"') WHERE id = $1;
UPDATE events SET payload = payload - 'debug' || '{"v": 2}'::jsonb WHERE id = $1;

-- Building JSON from rows (great for APIs: one query returns the nested document)
SELECT jsonb_build_object(
         'id', o.id,
         'customer', jsonb_build_object('id', c.id, 'email', c.email),
         'lines', (SELECT jsonb_agg(jsonb_build_object('sku', l.sku, 'qty', l.qty) ORDER BY l.line_no)
                   FROM order_lines l WHERE l.order_id = o.id))
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.id = $1;

-- PostgreSQL 17: JSON_TABLE turns JSON into rows and columns (SQL standard)
SELECT jt.* FROM events e,
  JSON_TABLE(e.payload, '$.lines[*]' COLUMNS (sku text PATH '$.sku', qty int PATH '$.qty')) AS jt
WHERE e.type = 'OrderPlaced';

When to use JSON columns: for truly variable or sparse attributes (product specs that differ by category, integration payloads stored as received, user preferences, event payloads), and for data that's always read and written as a whole. When not to: for fields you filter, join or aggregate on routinely, or that need constraints and foreign keys. Promote those to real columns (or generated columns). A schema made of a single jsonb column throws away the database's strongest features.

Other engines: MySQL JSON type (binary, with ->/->>, multi-valued indexes on arrays since 8.0.17); SQL Server stores JSON in nvarchar with JSON_VALUE/OPENJSON (and a native json type in recent versions); Oracle has native JSON (21c+) and JSON-relational duality views (23ai); SQLite has JSON functions and JSONB (3.45+).

Arrays

PostgreSQL has first-class array columns:

SQL
CREATE TABLE posts (id bigint PRIMARY KEY, tags text[] NOT NULL DEFAULT '{}');
CREATE INDEX posts_tags_gin ON posts USING gin (tags);

SELECT * FROM posts WHERE tags @> ARRAY['postgres', 'sql'];    -- contains all (GIN-indexable)
SELECT * FROM posts WHERE tags && ARRAY['rust', 'go'];          -- overlaps (any)
SELECT * FROM posts WHERE 'java' = ANY(tags);
SELECT id, unnest(tags) AS tag FROM posts;                       -- one row per element
SELECT array_agg(DISTINCT tag ORDER BY tag) FROM post_tags;     -- rows → array
SELECT * FROM orders WHERE id = ANY($1::uuid[]);                -- one array parameter instead of N bind params

Arrays are convenient for small, simple lists (tags, flags) and for passing sets of values as one parameter. If elements need their own attributes, constraints or FKs, use a child table.

Full-text search in SQL

LIKE '%word%' can't use a B-tree index and doesn't understand language. PostgreSQL has built-in full-text search: documents become a tsvector (normalised lexemes with positions), queries become a tsquery, and GIN indexes make matching fast:

SQL
ALTER TABLE products ADD COLUMN search tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(description, '')), 'B')
  ) STORED;
CREATE INDEX products_search_gin ON products USING gin (search);

SELECT id, name, ts_rank(search, q) AS rank
FROM products, websearch_to_tsquery('english', 'wireless "noise cancelling" -earbuds') AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;
-- Fuzzy and typo-tolerant matching: the pg_trgm extension (trigram similarity, GIN/GiST indexes)
-- Vector similarity (semantic search): the pgvector extension (chapter 63)

It's good enough for many applications: product search on modest catalogues, admin search, document search. Dedicated engines (Elasticsearch, OpenSearch, Solr, Meilisearch, Typesense) add BM25 relevance tuning, analysers per language, facets at scale, typo tolerance and distributed indexing (chapter 63). MySQL has FULLTEXT indexes, SQLite has FTS5, and SQL Server has full-text indexes.

Portability notes

Feature PostgreSQL MySQL 8.x SQLite SQL Server Oracle
Limit LIMIT/OFFSET, FETCH FIRST LIMIT LIMIT TOP, OFFSET … FETCH FETCH FIRST (12c+)
Upsert ON CONFLICT, MERGE (15+) ON DUPLICATE KEY UPDATE ON CONFLICT MERGE MERGE
RETURNING Yes (OLD/NEW in 18) No (LAST_INSERT_ID()) Yes (3.35+) OUTPUT RETURNING INTO
FULL OUTER JOIN Yes No Yes (3.39+) Yes Yes
FILTER on aggregates Yes No Yes No No
LATERAL LATERAL LATERAL (8.0.14+) No APPLY LATERAL/APPLY
String concatenation || CONCAT() (|| is OR by default!) || +/CONCAT ||
Booleans boolean TINYINT(1) Integers bit BOOLEAN (23ai+)
Identifier quoting "name" `name` "name" [name] "name"

Write portable SQL when you genuinely need several engines. Otherwise, use your database's strengths: the portability you give up is rarely worth the features you'd have to avoid.

Lab: SQL that's wrong, and SQL that's slow

PostgreSQL 16, with a generated dataset: 10,000 customers (9,000 of whom have ordered), 200,000 orders between January and May 2026, 3 lines per order, and one or two payment rows per order. Timings are the best of three runs.

Experiment 1: a LEFT JOIN undone by WHERE

"List every customer with their orders since 1 May":

SQL
SELECT … FROM cust c LEFT JOIN ord o ON o.cust_id = c.id AND o.placed_at >= '2026-05-01'   -- condition in ON
SELECT … FROM cust c LEFT JOIN ord o ON o.cust_id = c.id WHERE o.placed_at >= '2026-05-01' -- condition in WHERE
Text
customers listed: condition in ON → 10,000 | same condition in WHERE → 9,000 (the 1,000 customers without orders since 1 May vanish)

The left join produced a NULL-filled row for each customer without a matching order; then WHERE o.placed_at >= … evaluated to unknown on those NULLs and removed them, turning the left join back into an inner join without any error. Conditions on the right-hand table of a left join belong in ON; conditions on the left table belong in WHERE. Reviewers should flag any WHERE that references the optional side of an outer join (other than IS NULL checks for anti-joins).

Experiment 2: fan-out inflating revenue

SQL
SELECT sum(total) FROM ord;                                                                   -- correct
SELECT sum(o.total) FROM ord o JOIN ol ON ol.ord_id = o.id JOIN pay p ON p.ord_id = o.id;      -- "add the lines and payments"
Text
revenue: sum(total) over orders = 3,197,210,000 | after joining lines (3 per order) and payments → 10,550,910,000 (3.30×)

Each order became 3 rows (one per line), and the 10% of orders with two payment rows became 6: joining two independent one-to-many relationships multiplies them by each other. The query ran without error and produced a revenue figure 3.3 times too high, the kind of number that ends up in a board report. Aggregate each child table separately (in subqueries or CTEs, grouped by the parent key) and then join the aggregates, or use count(DISTINCT …) where only counting is needed. A quick check: compare count(*) before and after adding each join.

Experiment 3: running totals

Text
running total over 20,000 orders: window function 23.7 ms | correlated subquery 17,731 ms (748× slower)

The correlated subquery (SELECT sum(total) FROM ord i WHERE i.id <= o.id for every row) recomputes the sum from scratch per row: O(n²) work, 200 million row visits. The window function sum(total) OVER (ORDER BY id) sorts once and keeps a running sum: O(n log n). Before window functions (SQL:2003, PostgreSQL 8.4 in 2009) people wrote the self-join form; it still appears in old code and ORM-generated queries.

Experiment 4: the latest order for every customer

Text
row_number() window : 86.7 ms, 9,000 rows
DISTINCT ON         : 91.9 ms, 9,000 rows
LATERAL + index     : 21.2 ms, 9,000 rows

All three return the same rows. The first two read and sort (or scan the index of) all 200,000 orders and keep one per customer. The LATERAL form runs a tiny subquery per customer (ORDER BY placed_at DESC LIMIT 1) that the index on (cust_id, placed_at DESC) answers by reading one entry: 4× faster here, and the gap grows with the number of orders per customer. When there are many rows per group and an index matching (group, sort key), the per-group lookup wins; with few rows per group, a single pass is fine.

Experiment 5: days with no sales

Text
GROUP BY day: 3 rows | with generate_series calendar: [('2026-10-01', 500), ('2026-10-02', 300), ('2026-10-03', 0), ('2026-10-04', 0), ('2026-10-05', 700)]

GROUP BY can only produce groups for values that exist, so a chart built from it silently skips days with no sales and draws a straight line across the gap. Generate the full set of buckets (generate_series of dates, or a calendar table) and left-join the data onto it, with coalesce(…, 0).

Try it yourself

  1. Rewrite experiment 2 correctly with two CTEs (lines_per_order, paid_per_order) and confirm the total matches sum(total).
  2. Run experiment 4 with EXPLAIN ANALYZE and find the node that reads 200,000 rows in the first two plans and 9,000 index probes in the third.
  3. Write a recursive CTE that expands a category(id, parent_id, name) tree into full paths ("Food > South Indian > Breakfast").
  4. Compute a 7-day moving average of daily revenue with a window frame (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) over experiment 5's calendar.

Revision sheet: SQL

Key ideas

  • Declarative: describe the result; the planner chooses the method. Logical evaluation order: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT (window functions) → DISTINCT → ORDER BY → LIMIT/OFFSET.
  • Joins: inner, left/right/full outer, cross, self, semi (EXISTS, IN), anti (NOT EXISTS), LATERAL; ON vs WHERE conditions for outer joins; USING and NATURAL (avoid the latter).
  • Aggregation: count(*) vs count(col) vs count(DISTINCT col), FILTER (WHERE …), GROUPING SETS, ROLLUP, CUBE; fan-out from joining several one-to-many relationships.
  • Subqueries and CTEs: scalar, correlated, derived tables; CTEs (inlined by default since PostgreSQL 12, MATERIALIZED to force); recursive CTEs for trees and graphs.
  • Window functions: PARTITION BY, ORDER BY, frames (ROWS/RANGE/GROUPS), ranking (row_number, rank, dense_rank), offset (lag, lead, first_value), running aggregates.
  • Set operations: UNION (dedupes) vs UNION ALL, INTERSECT, EXCEPT.
  • Modifying data: INSERT … ON CONFLICT (upsert), MERGE, UPDATE … FROM, DELETE … USING, RETURNING.
  • PostgreSQL extras: DISTINCT ON, arrays, jsonb operators, generate_series, FILTER, full-text search.

Numbers to remember

  • Lab: a misplaced WHERE dropped 1,000 of 10,000 customers; double fan-out inflated revenue 3.3×; a correlated running total was 748× slower than a window function; LATERAL with an index was 4× faster for latest-per-group.

Pitfalls

  • Filtering the optional side of an outer join in WHERE.
  • Summing parent values after joining children (fan-out); count(*) after outer joins.
  • NOT IN with NULLs; = NULL instead of IS NULL.
  • SELECT * in application queries; ORDER BY missing for LIMIT or pagination.
  • Correlated subqueries where joins or windows would do; UNION where UNION ALL is meant.
  • Gaps in time series from grouping only existing values.

Glossary

  • Join predicate: the condition pairing rows from two tables.
  • Fan-out: row multiplication from joining a one-to-many relationship.
  • Semi-join / anti-join: keep rows with / without a match, without duplicating them.
  • Window frame: the rows around the current row a window function uses.
  • CTE: common table expression, a named subquery.
  • LATERAL: a subquery that can reference columns from earlier tables in the FROM clause.