2 · SQL & databases

3. Advanced SQL: Windows, CTEs and Query Plans

Window functions, recursive CTEs, indexing and reading EXPLAIN output.

11 min read · 3 MCQs

Window functions

A window function computes across a set of rows related to the current row without collapsing them: ROW_NUMBER, RANK, LAG/LEAD, and running totals with SUM(...) OVER (PARTITION BY ... ORDER BY ...). They replace most self-joins and correlated subqueries.

WITH monthly AS (
  SELECT date_trunc('month', created_at) AS m,
         customer_id,
         SUM(total_cents) AS cents
  FROM orders
  GROUP BY 1, 2
)
SELECT m, customer_id, cents,
       SUM(cents) OVER (PARTITION BY customer_id ORDER BY m) AS lifetime_cents,
       RANK()     OVER (PARTITION BY m ORDER BY cents DESC)  AS rank_in_month
FROM monthly;

CTEs and recursion

Common table expressions name intermediate results and make long queries readable; recursive CTEs walk hierarchies such as org charts or category trees. Always bound recursion depth to avoid runaway queries.

Indexes and plans

A B-tree index accelerates equality and range predicates and can serve ORDER BY; composite index column order matters and follows the leftmost-prefix rule. Wrapping an indexed column in a function usually disables the index. Read EXPLAIN ANALYZE for sequential scans on large tables, bad row estimates and spills to disk.

Chapter quiz

3 questions · pass mark 75%
  1. 1. Window functions differ from GROUP BY because they…

  2. 2. An index on (a, b) helps a query filtering only on…

  3. 3. WHERE lower(email) = 'x' on an index over email typically…

Answer every question to submit. Progress for da-03 is saved in this browser.