SteelReed

Search

Search posts, questions…

4. Database & SQL

Subqueries, CTEs, recursive CTEs, window functions and temporary tables

When a subquery re-runs for every row, when a CTE is inlined or materialized, walking trees with WITH RECURSIVE and stopping cycles, window functions whose default frame gives wrong answers, top-N per group, de-duplication, when you need a temporary table; measured on PostgreSQL 18 with 1 million rows, plus how to review SQL an AI wrote.

19 Nov 20268 min readMid

–

1. The problem

A report "the customer's largest order, next to each order" takes 0.3 s for 2,000 orders and 9.7 s for 200,000. Rewritten as one JOIN, the same result takes 127 ms. No error anywhere, just steps split the wrong way.

2. Key idea

You write the result you want; the database picks how to run it. How you split the steps decides whether the optimizer sees the whole query or runs blind pieces. Write the readable version first, then open EXPLAIN ANALYZE to check the plan does what you think.

Trap Symptom Root cause
Repeated subquery time grows with outer rows SubPlan runs once per row
Materialized CTE a readability refactor is hundreds of times slower the CTE is used twice; conditions aren't pushed inside
Endless recursion runs until timeout the tree data has a cycle
RANGE frame odd running totals on days with two orders tied rows count as "the current row"
Tool Use when Don't use when
CTE (WITH) splitting a long query into named steps you want to "cache" a step for speed
WITH RECURSIVE trees, graphs, generating date series data may contain cycles you haven't guarded against
Window functions ranking, running totals, comparing with the previous row you need one row per group (GROUP BY suffices)
LATERAL ... LIMIT top-N per group with an index in the right order ranking the whole dataset
Temp tables large, reused intermediate results, batches OLTP requests, behind PgBouncer transaction mode

3. In SQL

SQL
-- Fast: aggregate once and JOIN, instead of a subquery in SELECT
SELECT o.id, m.max_amount
FROM orders o
JOIN (SELECT customer_id, max(amount) AS max_amount
      FROM orders GROUP BY customer_id) m USING (customer_id);
 
-- Tree: one query, cycles stopped with CYCLE (PostgreSQL 14+)
WITH RECURSIVE sub AS (
  SELECT id, parent_id FROM node WHERE id = 1
  UNION ALL
  SELECT n.id, n.parent_id FROM node n JOIN sub s ON n.parent_id = s.id
) CYCLE id SET is_cycle USING path
SELECT id FROM sub WHERE NOT is_cycle;
 
-- Correct running total: state ROWS and a tie-breaker
SELECT day, amount,
       sum(amount) OVER (ORDER BY day, id ROWS UNBOUNDED PRECEDING) AS running
FROM ord;

Other databases: MySQL 8.0+ has CTEs, WITH RECURSIVE (stops at 1,000 iterations by default), window functions and LATERAL; SQL Server uses CROSS APPLY instead of LATERAL.

Top-N per group, deduplication and temp tables
  • Top-N per group: row_number() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) then filter rn <= 3; or LATERAL (... ORDER BY amount DESC LIMIT 3) with an index on (customer_id, amount DESC).
  • Deduplication: number rows with row_number() over the duplicate key and delete rn > 1; always include a tie-breaker in ORDER BY so the result is deterministic.
  • last_value with the default frame returns the current row; you need ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
  • Temp tables: autovacuum doesn't ANALYZE them, so run ANALYZE after loading. Use ON COMMIT DROP; behind PgBouncer transaction mode, a temp table can land on a different connection.
  • Forcing a CTE plan: AS MATERIALIZED or AS NOT MATERIALIZED (PostgreSQL 12+).

4. Working with AI

Hand to AI: drafting reports from business descriptions, generating test data with ties and NULLs, turning correlated subqueries into JOINs, explaining a long plan.

Check yourself in AI-written code:

  • OVER (ORDER BY ...) for running totals has ROWS and a tie-breaker (id).
  • WITH RECURSIVE has a guard: a path, CYCLE or a depth limit.
  • No correlated subquery in SELECT over many outer rows (look for SubPlan in the plan).
  • CTEs used twice or marked MATERIALIZED have had their plan checked.
  • Every ranking or running-total query has a test with tied data.

5. Exercises

Exercise 1: Review a running total

The AI wrote SELECT id, day, amount, sum(amount) OVER (ORDER BY day) AS running FROM ord ORDER BY day and says "tested, the total is right". Real data has several orders per day. Find the bug, give test data that proves it, fix it.

Solution 1

No frame is stated, so it's RANGE ... CURRENT ROW. Orders on the same day are all "the current row", so every order that day gets the whole day's total. The end-of-day total is still right, so the "total is right" test stays green.

Test data: one order of 10 on Nov 1, two orders of 20 and 30 on Nov 2. Expected running totals 10, 30, 60; actual 10, 60, 60.

Fix: sum(amount) OVER (ORDER BY day, id ROWS UNBOUNDED PRECEDING).

Exercise 2: Read an incident after a "refactor only" PR

A PR "split the report query into CTEs for readability" is merged. The single-customer query goes from 0.2 ms to 90 ms; the new plan shows CTE Scan on x above Seq Scan on orders (rows=1000000). The query uses CTE x twice. Diagnose it, say what to do in 15 minutes, fix the root cause.

Solution 2
  • Diagnosis: used twice, the CTE gets materialized: PostgreSQL computes all 1 million rows into an intermediate result before filtering by customer. The outer customer_id = ? isn't pushed inside.
  • 15 minutes: revert the PR or add AS NOT MATERIALIZED, and confirm with EXPLAIN ANALYZE that the plan returns to an Index Scan.
  • Root fix: move the filter into the CTE. Add to the review checklist: CTEs used twice must come with a plan.

Summary

  • Correlated subqueries slow down with outer rows; rewrite as a JOIN against an aggregate.
  • CTEs used twice get materialized; check the plan.
  • WITH RECURSIVE always has a depth limit, a path or CYCLE.
  • Running totals state ROWS and a tie-breaker; beware the default RANGE.
  • Temp tables need ANALYZE and reliable cleanup.

Further reading: SQL exercises: JOIN and GROUP BY.

Practice interview questions on this topic

All SQL & Query Tuning questions →

Loading comments…
Next on the roadmapSQL practice: joins, GROUP BY and NULL traps on a library database