Advanced SQL: Window Functions, CTEs, and Subqueries Questions
Analytical SQL for complex problems: window functions (ranking, running totals, LAG/LEAD, partitioned aggregates), common table expressions including recursive CTEs, and scalar, nested, and correlated subqueries. Covers when each construct is the right tool and how they compose for multi-step analysis. The differentiator between basic and senior SQL competence.
EXPLAIN ANALYZE on a query using SUM(...) OVER (PARTITION BY user_id ORDER BY ts) shows a large Sort and a WindowAgg node with high disk usage, and the query times out on a large table. Walk through how you'd diagnose this from the plan and what you'd try first: indexing to match the partition/order columns, reducing partition cardinality, or restructuring the query. Then, separately, take a query that computes a per-user running total via a self-join or a correlated subquery per row and rewrite it as a single-pass window function, explaining why the rewrite is asymptotically better.
Sample Answer
Direct answer: For the slow SUM(...) OVER (PARTITION BY user_id ORDER BY ts) query, diagnose in this order: first confirm whether the partition key is skewed (a handful of users with far more rows than everyone else), since no indexing fixes that; then check whether an index on (user_id, ts) lets the engine skip the explicit sort the plan is paying for; only after those are ruled out or exhausted does restructuring the query (pre-aggregating, or bounding the frame) become the next lever. Separately, a per-user running total written as a self-join or a correlated subquery per row is quadratic work in disguise: rewriting it as a single window function turns an O(n^2)-per-partition comparison into one O(n log n) sort plus a single O(n) pass, because the window function reuses the previous row's accumulated state instead of re-scanning all prior rows from scratch for every single row.
Approach: diagnosing the slow EXPLAIN ANALYZE
A plan showing a large Sort and a WindowAgg with high disk usage on a huge table, timing out, is telling you the sort and the per-partition running-sum state both outgrew available memory. Work through these in order:
- Check for partition-key skew first.
SELECT user_id, COUNT(*) FROM tx GROUP BY user_id ORDER BY 2 DESC LIMIT 10;If a small number of users dominate row counts, that alone can make one partition's window state balloon regardless of any indexing, and the fix is closer to "cap or pre-aggregate that user's history" than "tune the query." - Add or confirm an index matching the partition and order columns:
CREATE INDEX ON tx(user_id, ts);. If the engine can scan in that order already, it can skip the explicitSortnode in the plan entirely, which is usually the single biggest win, since sorting a huge table is often the dominant cost, not the window computation itself. - Reduce partition cardinality or bound the frame if the running sum only actually needs to look back a fixed distance (e.g.
ROWS BETWEEN 29 PRECEDING AND CURRENT ROWfor a 30-row trailing sum) rather than the full-partitionUNBOUNDED PRECEDINGdefault; a bounded frame needs a small sliding buffer instead of the whole partition's history. - Restructure only if the above aren't enough: pre-aggregate to a coarser grain before windowing (e.g., roll transactions up to one row per user per day first, if daily granularity is acceptable), or maintain an incrementally-updated running-total table so the expensive full recompute never has to happen live.
Approach: self-join / correlated subquery to single-pass window function
-- BEFORE: self-join running total (quadratic)
SELECT t1.user_id, t1.ts, t1.amount,
SUM(t2.amount) AS running_total
FROM tx t1
JOIN tx t2 ON t2.user_id = t1.user_id AND t2.ts <= t1.ts
GROUP BY t1.user_id, t1.ts, t1.amount
ORDER BY t1.user_id, t1.ts;
-- AFTER: single-pass window function
SELECT user_id, ts, amount,
SUM(amount) OVER (PARTITION BY user_id ORDER BY ts
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM tx
ORDER BY user_id, ts;
Key points
- The self-join re-derives every row's running total independently, from scratch, by joining it against every earlier row in its partition and summing; the window function computes it incrementally, carrying forward one running accumulator per partition as it walks the sorted rows once.
- A correlated subquery version (
SELECT SUM(amount) FROM tx t2 WHERE t2.user_id = t1.user_id AND t2.ts <= t1.tsrun once per outer row) has the identical cost shape as the self-join: it re-executes a full sub-scan for every outer row. - Both rewrite targets need a tiebreaker in
ORDER BY(an id column alongsidets) iftscan repeat within a user, so the running total's row-by-row order is reproducible.
Worked example
Verified in DuckDB against tx(user_id, ts, amount) with rows (1,'01-01',100), (1,'01-02',50), (1,'01-03',30), (2,'01-01',20), (2,'01-02',40), both queries return the identical running totals for user 1: 100, 150, 180, and for user 2: 20, 60. The rewrite changes performance characteristics only, never the result.
Complexity
The self-join (or correlated subquery) does, for every row in a partition of size k, a scan/join against up to k earlier rows, so total work per partition is O(k^2), and summed across all partitions that's proportional to the sum of squared partition sizes rather than the total row count n; for a table dominated by one huge partition, this degrades badly. The window-function version requires one sort of each partition (O(k log k), or free if an index already provides that order) followed by a single incremental pass (O(k)) that adds each row's value to a running accumulator, giving O(n log n) overall in the worst case, or O(n) if the sort is avoided via an index.
Edge cases
- Duplicate
tsvalues within a user: the self-join'st2.ts <= t1.tscondition includes all tied rows for every one of them, which can double- or triple-count depending on how many rows share that timestamp, unless a tiebreaker column is added to strictly order ties; the window-function rewrite has the identical ambiguity if it relies on the defaultRANGEframe (which groups ties together) instead of an explicitROWSframe with a tiebreaker inORDER BY. - An empty or single-row partition: both versions correctly return that row's own value with nothing summed in from elsewhere.
NULLamounts:SUM()ignoresNULLs in both the self-join's aggregate and the window function, so behavior matches; aNULLtssorts as its own peer group under the default ordering rules and needs the sameNULLS FIRST/NULLS LASTconsideration in either version.
Trade-offs & pitfalls
The subtle trap in the diagnosis playbook is reaching for "add an index" before checking for skew: an index fixes a sort-dominated plan, but it does nothing for a single oversized partition whose per-partition window state simply can't shrink no matter how the rows are ordered. Conversely, once the self-join is rewritten to a window function, it's tempting to assume the query is now cheap; if the partition is still enormous and the frame is still the unbounded default, the window function still has to buffer a large amount of per-partition state, just with much better asymptotics than the self-join it replaced, not zero cost.
Explain the differences between ROW_NUMBER(), RANK(), and DENSE_RANK(): how each handles ties and whether gaps appear afterward. Using a small sample of salespeople and amounts with a tie for second place, show what each function returns, and say which one you'd pick for a leaderboard versus a strict top-N dedup, and why. Then discuss how the choice interacts with computing a rank change from the previous period (did this item's rank improve or decline compared to last month), and what you'd want to clarify with the business before committing to one of the three for a customer-facing leaderboard.
Sample Answer
Direct answer: All three assign a position to each row within an ordered partition, and differ only in how they treat ties. ROW_NUMBER() never ties: even equal values get distinct, arbitrary sequential numbers. RANK() gives tied rows the same number, then skips ahead by the count of tied rows, leaving a gap. DENSE_RANK() also gives tied rows the same number, but the next distinct value always gets the very next integer, so there's never a gap. For a leaderboard, where "2nd place" should mean something to a human reading it, RANK() is usually right, since the gap after a tie correctly reflects how many people are ahead. For a strict top-N dedup where you need exactly N rows no matter what, ROW_NUMBER() is the only one of the three that guarantees that count.
Structured elaboration
Sample data, salespeople and revenue, with a tie for 2nd place:
| salesperson | amount |
|---|---|
| Alice | 500 |
| Bob | 400 |
| Carol | 400 |
| Dan | 300 |
SELECT salesperson, amount,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn,
RANK() OVER (ORDER BY amount DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY amount DESC) AS dr
FROM sales
ORDER BY amount DESC, salesperson;
Verified in DuckDB:
| salesperson | amount | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|---|
| Alice | 500 | 1 | 1 | 1 |
| Bob | 400 | 2 | 2 | 2 |
| Carol | 400 | 3 | 2 | 2 |
| Dan | 300 | 4 | 4 | 3 |
Bob and Carol tie at 400. ROW_NUMBER still splits them into 2 and 3 (an arbitrary tiebreak, since nothing in the data distinguishes them, so this ordering is not guaranteed stable across re-runs without an explicit tiebreaker column). RANK gives both a 2, then Dan jumps straight to 4, correctly reflecting that 2 people are ahead of him. DENSE_RANK also gives both a 2, but Dan gets 3, since DENSE_RANK only counts distinct amount values seen so far, not rows.
Which to pick, and why:
- Leaderboard (display to end users):
RANK(). "2nd place" shared by two people, then the next distinct entry correctly shown as "4th," matches how humans read a real ranked competition: the gap communicates that two people are ahead of the next name. - Strict top-N dedup (e.g., "keep exactly the 3 most recent orders per customer"):
ROW_NUMBER(), filtered torn <= 3. It's the only one of the three guaranteed to produce exactly 3 rows per partition, because it never ties;RANKorDENSE_RANKfiltered the same way can return more than 3 rows if a tie straddles the cutoff.
Rank change from the previous period: combine RANK() with LAG() to compare a person's rank this period against last period.
WITH ranked AS (
SELECT salesperson, month, amount,
RANK() OVER (PARTITION BY month ORDER BY amount DESC) AS rnk
FROM monthly_sales
)
SELECT salesperson, month, amount, rnk,
LAG(rnk) OVER (PARTITION BY salesperson ORDER BY month) AS prev_rnk,
LAG(rnk) OVER (PARTITION BY salesperson ORDER BY month) - rnk AS rank_improvement
FROM ranked
ORDER BY salesperson, month;
Verified in DuckDB against a 2-month dataset (Alice 500 then 300, Bob 400 then 450, Carol 400 then 450, Dan 300 then 500): Alice goes from rank 1 to rank 4 (rank_improvement = -3, a decline), Dan goes from rank 4 to rank 1 (rank_improvement = +3, an improvement), and Bob and Carol, tied at rank 2 in both months, show rank_improvement = 0. The choice of ranking function directly changes what "0 rank change" means: under RANK(), Bob and Carol's tie is honestly reflected as "no change" in both periods; under ROW_NUMBER(), their arbitrary 2-vs-3 split could make one of them look like they improved or declined purely due to tiebreak order, which is a false signal, not a real rank change.
What to clarify with the business before committing to one of the three:
- Does "2nd place" need to be an honest, deterministic reflection of ties (favoring
RANK/DENSE_RANK), or does the leaderboard promise exactly one name per position no matter what, which forces a tiebreaker column (like earliest achievement time) rather than accepting an arbitraryROW_NUMBERsplit? - If two people tie and both show "rank 2," should the next person see "rank 3" (no visible gap, i.e.
DENSE_RANK) or "rank 4" (a gap that signals two people are ahead, i.e.RANK)? Both are defensible; the business's mental model of "how many people did I beat" decides it. - For the period-over-period comparison, does a tie count as "no change" even if the underlying score moved, or should the business want ties broken by a secondary metric so genuine movement is never masked as a flat rank?
Trade-offs & pitfalls
The common wrong turn is reaching for ROW_NUMBER() on a public leaderboard because "it's simpler," which silently manufactures a fake distinction between two people who are, by the actual data, exactly tied; that's a correctness bug dressed up as a display choice. The opposite mistake is using RANK() or DENSE_RANK() for a strict top-N filter and being surprised when a report returns 5 rows instead of 3 because two rows tied at the cutoff; if that surprises a downstream consumer, it needs an explicit deterministic tiebreaker in the ORDER BY (an id, a timestamp) so ROW_NUMBER() becomes reproducible instead of arbitrary.
A query that used to run in seconds now takes minutes after a rewrite into several CTEs for readability. The result is still correct, but the warehouse scan shows repeated work on the same large tables. How would you investigate whether the CTE structure is helping or hurting, and what would you change first if the execution plan looks suspicious?
Sample Answer
How I would investigate
I would compare the query profile, not just the SQL text. A CTE, or common table expression, is a named subquery. On some warehouses it is inlined, and on others it may be materialized or repeatedly scanned. I would look for repeated reads of the same large table, lost predicate pushdown, and big intermediate results.
First checks
- Run
EXPLAINor the warehouse query profile. - See whether the same base table is scanned more than once.
- Check whether filters are applied after large joins instead of before them.
- Compare row counts at each step to find the explosion point.
What I would change first
If a suspicious CTE is referenced once, I would inline it or fold it into the parent query. If it is reused multiple times, I would stage the filtered result in a temp table or a materialized table so the expensive work happens once.
Rule of thumb
Readability is good, but if separate CTEs each reread a billion-row fact table, the query gets slower. The fix is usually to push filters earlier, keep only needed columns, and avoid recomputing the same join or aggregation in multiple branches.
You're computing a rolling sum over the last 7 readings for a sensor, but readings arrive at irregular intervals (sometimes seconds apart, sometimes hours). Explain why RANGE BETWEEN on the timestamp column doesn't do what most people expect here, and what the robust alternative is.
Sample Answer
Direct answer: "Last 7 readings" is a count-based request, but RANGE BETWEEN is a value-based frame: RANGE BETWEEN INTERVAL '6 seconds' PRECEDING AND CURRENT ROW doesn't mean "6 rows back," it means "every row whose timestamp is within 6 seconds of this row's timestamp." On irregular data that value window can contain anywhere from zero rows (during a quiet stretch) to dozens (during a burst), so no matter what interval you plug in, RANGE cannot deliver a stable "last 7 readings" semantic. The robust alternative is a purely positional frame, ROWS BETWEEN 6 PRECEDING AND CURRENT ROW, which always includes exactly the 7 most recent physical rows in sort order, independent of how close together or far apart their timestamps happen to be.
Structured elaboration
- Both frame types accept syntax that looks parallel (
BETWEEN 6 PRECEDING AND CURRENT ROW), so it's easy to assume the "6" means the same thing in each. It doesn't: ROWS's number is a row count; RANGE's number (or interval) is a distance in the units of whatever you ORDER BY. - On genuinely irregular timestamps, a RANGE frame's row count swings with local reading density: a burst of readings a second apart puts many rows inside even a small interval; a gap of hours puts zero preceding rows inside that same interval. There is no fixed interval value that reliably captures "the last 7" across both regimes, because RANGE was never counting rows in the first place.
- The dangerous part is that this fails silently. There's no error, no exception, just a differently-sized sum or average computed at every row depending on local reading density. It shows up downstream as a suspiciously spiky or suspiciously flat metric, not a crash, which makes it slow to diagnose.
Worked example
Table readings(id, ts, value): a burst of 4 readings 1 second apart, then a 3-hour gap, then 4 more readings 1 second apart.
SELECT id, ts, value,
COUNT(*) OVER (ORDER BY ts
RANGE BETWEEN INTERVAL '6 seconds' PRECEDING AND CURRENT ROW) AS n_range_6s,
COUNT(*) OVER (ORDER BY ts
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS n_rows_7
FROM readings
ORDER BY ts;
Verified in DuckDB. n_range_6s comes back 1, 2, 3, 4, 1, 2, 3, 4: it resets to 1 right after the 3-hour gap even though that row is the 5th reading overall, because the 3-hour gap (10,800 seconds) is far outside the 6-second value window, so RANGE genuinely finds nothing preceding it within range. n_rows_7 comes back 1, 2, 3, 4, 5, 6, 7, 7: a smooth, always-correct count of the most recent readings, capped at 7, with no sensitivity to how close together the timestamps are.
Key points
- ROWS's bound is a count; RANGE's bound is a distance, and confusing the two is the entire trap.
- No choice of interval fixes RANGE for a count-based requirement on genuinely irregular data: shrink it and you miss rows during quiet stretches, widen it and you pull in far too many during bursts.
- The query never errors either way, so this bug is discovered from a metric that looks wrong, not from a stack trace.
Complexity
ROWS with a fixed count of preceding rows is O(n) after the initial O(n log n) sort: an engine can maintain the sum incrementally, dropping the row that falls off the trailing edge as it adds the new one. RANGE frames over irregular data are also computed incrementally by most engines, but because the number of rows in frame varies row to row, the per-row work is proportional to how many rows enter or leave the frame at that step, which is data-dependent rather than a fixed constant.
Edge cases
- Fewer than 7 total readings so far: both frames just use however many rows exist; this isn't a bug in either version, it's the expected boundary behavior at the start of the series.
- Duplicate timestamps: RANGE treats exactly-equal timestamps as peers (all included or all excluded together), which can push its row count up further inside a dense burst; ROWS is unaffected since it only cares about physical position.
- If the ordering column is a raw numeric epoch rather than a proper TIMESTAMP, the RANGE trap is identical, just with the units being "whatever the number represents" instead of an explicit interval; the type of the column doesn't change the underlying value-vs-count distinction.
Trade-offs & pitfalls
This isn't "always prefer ROWS." If the actual requirement is a genuine time-bounded window ("everything from the last 10 minutes," not "the last 7 readings"), RANGE with an appropriately chosen interval is the correct tool and ROWS is wrong for that job. Match the frame type to what the requirement is actually counting: a quantity of readings, or a span of time.
A common middle-ground need is "the last 7 readings, but only if they're within some sane recency window," so a stale burst from last week doesn't get blended with today's value. Neither ROWS nor RANGE alone expresses "both a max count and a max time span"; that needs ROWS for the count plus a separate filter (WHERE or HAVING) checking the oldest included timestamp, or a two-pass approach.
This is a different failure shape from a series with a handful of whole missing calendar days, where the frame boundary and the business unit of "day" still line up cleanly and only the sample size shrinks. Here the irregularity is sub-day and unbounded in either direction, which is what makes RANGE unusable for a count-based ask no matter how the interval is tuned.
You need to add a per-row calculated field to a report, for example each customer's total spend next to their city's average spend. Compare doing this with a scalar subquery in the SELECT list versus a LEFT JOIN or CTE. When is the subquery-in-SELECT approach genuinely fine, and when does it become a problem?
Sample Answer
A scalar subquery in the SELECT list is fine for a per-row calculated field when the lookup is cheap and well-indexed relative to the size of the result set; it becomes a problem once the report is large enough, or run often enough, that re-deriving the same group value for every row starts to dominate the query's cost. For "each customer's total spend next to their city's average spend," a correlated scalar subquery and a LEFT JOIN/CTE (common table expression) against a pre-aggregated city average produce identical results; the choice is about cost and clarity, not correctness.
Scalar subquery in SELECT
SELECT
c.customer_id,
c.city,
c.total_spend,
(
SELECT AVG(c2.total_spend)
FROM customers c2
WHERE c2.city = c.city -- correlated to the outer row's city
) AS city_avg_spend
FROM customers c;
LEFT JOIN / CTE against a pre-aggregated average
WITH city_avg AS (
SELECT city, AVG(total_spend) AS avg_spend
FROM customers
GROUP BY city
)
SELECT
c.customer_id,
c.city,
c.total_spend,
ca.avg_spend AS city_avg_spend
FROM customers c
LEFT JOIN city_avg ca ON ca.city = c.city;
Key points
- Both queries produce the exact same output; the CTE version computes each city's average exactly once, in one grouped pass, then joins it back.
- The scalar-subquery version recomputes the average for every row whose city hasn't already had it cached by the engine; whether that's "recomputed per row" in the literal execution plan, or optimized into something closer to the join, depends on the engine.
LEFT JOINpreserves customers whose city doesn't match any row incity_avg(which shouldn't happen here sincecity_avgis derived from the same table, but matters when the averaged table is a separate dimension table that might not have every city represented).
Complexity
The scalar-subquery form costs, in the worst case a naive planner takes, O(rows) times O(cost of one AVG over that customer's city), which for an unindexed city column means a full table scan per row: O(rows²) overall. With an index on customers(city, total_spend), each per-row lookup becomes a much cheaper index range scan, but it's still work repeated once per row rather than once per distinct city. The CTE/join form computes the per-city average in a single GROUP BY pass (O(rows) with a hash or index-based aggregate), then joins it back in roughly O(rows) more, for a total that scales with the number of distinct cities touched by the aggregation, not the number of output rows.
Worked example
Five customers across two cities: Austin has spends 500, 700, 300 (average 500); Denver has spends 900, 300 (average 600). Both queries above, run against this exact data, return the same five rows with city_avg_spend of 500 for every Austin customer and 600 for every Denver customer. (Verified by executing both queries against SQLite 3.51.)
| customer_id | city | total_spend | city_avg_spend |
|---|---|---|---|
| 1 | Austin | 500 | 500 |
| 2 | Austin | 700 | 500 |
| 3 | Austin | 300 | 500 |
| 4 | Denver | 900 | 600 |
| 5 | Denver | 300 | 600 |
Trade-offs and pitfalls
The scalar subquery is genuinely fine for a small ad-hoc report, a lookup by a unique/primary key (guaranteed one row, cheap either way), or a dataset small enough that the difference is immaterial; it's also the more concise and arguably more readable form for a single simple lookup. It becomes a problem at report scale: thousands-plus rows sharing a modest number of distinct groups (cities, departments, categories) is exactly the shape where recomputing the same aggregate per row wastes work that a single GROUP BY pass would do once. The other failure mode to watch for is correctness, not performance: a correlated scalar subquery must return at most one row, so if the "average" were instead something that could legitimately return multiple rows for a city (a bug, a data-quality issue, or a mismodeled one-to-many relationship), the query would error at runtime rather than silently returning something wrong, which is at least a fail-loud outcome worth knowing about before it surprises you in production.
Unlock Full Question Bank
Get access to all Advanced SQL: Window Functions, CTEs, and Subqueries interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.