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.
You want to filter to customers whose cumulative spend over the year exceeds a threshold, where cumulative spend is computed with a window function. Explain why you can't just put the window function in the WHERE clause, and write the query using a CTE or subquery wrapper instead.
Sample Answer
Window functions are evaluated after WHERE filters rows, so a window function's result doesn't exist yet at the point WHERE runs; SQL simply doesn't allow referencing one there (or in GROUP BY, for the same reason). To filter on a cumulative spend computed with a window function, compute it first in a CTE (common table expression, a named WITH block) or subquery, then filter the outer query against that already-computed column.
Approach
WITH customer_year_spend AS (
SELECT
customer_id,
order_id,
order_date,
amount,
SUM(amount) OVER (
PARTITION BY customer_id, EXTRACT(YEAR FROM order_date)
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_spend
FROM sales
)
SELECT DISTINCT customer_id
FROM customer_year_spend
WHERE cumulative_spend > 1000;
Key points
- The window function runs inside the CTE, over the full row set; the outer query's
WHEREfilters the CTE's already-materialized output, which is a normal column at that point, not a window function call. - The explicit
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWframe matters: without it, the default frame for anORDER BY-bearing window isRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which groups every row sharing the sameORDER BYvalue (here, the sameorder_date) into one combined total for all of them, not a true row-by-row running sum. - Because
amountis non-negative, the cumulative sum only ever increases through the year, so "the running total ever exceeds 1000" and "the year-end total exceeds 1000" pick out the exact same set of customers;DISTINCT customer_idover any row that clears the threshold is equivalent to filtering on the final total.
Why ROWS matters here: the RANGE default-frame trap
Two orders for the same customer on the same order_date (200 on 2024-03-10 and 150 on 2024-03-10, following an earlier 100 on 2024-01-05) expose the bug directly. With the default RANGE frame, both same-day rows are treated as peers and both get the combined total of all peers as their cumulative value (450 for both), instead of the running total accumulating row by row (300 after the first of the two, 450 after the second). ROWS fixes this because it counts physical rows up to the current one, not "all rows with the same ORDER BY value."
| order_id | order_date | amount | cumulative (ROWS, correct) | cumulative (RANGE, default, buggy) |
|---|---|---|---|---|
| 1 | 2024-01-05 | 100 | 100 | 100 |
| 2 | 2024-03-10 | 200 | 300 | 450 |
| 3 | 2024-03-10 | 150 | 450 | 450 |
(Verified by executing both the ROWS-framed and RANGE-framed versions of this window against the same data in SQLite 3.51; the RANGE result matches the buggy pattern exactly as shown.)
Complexity
Computing the window function is one ordered pass per partition: O(n log n) if the engine has to sort by (customer_id, order_date, order_id), or close to O(n) if an existing index already provides that order. The outer WHERE/DISTINCT is a single O(n) filter and de-duplication pass over the CTE's output. This is the same total cost as computing a plain GROUP BY/HAVING total would be; the window function version costs more only in the sense that it materializes a row per order instead of collapsing straight to one row per customer.
Edge cases
- Same-
order_dateorders: handled correctly only with the explicitROWSframe, as shown above; this is the single most common way this pattern silently breaks. - Negative amounts (refunds): if
amountcan go negative, the cumulative sum is no longer monotonically increasing, and "any row exceeds the threshold" is no longer equivalent to "the year-end total exceeds the threshold"; in that case you must filter on the maximum cumulative value per customer-year, not just any exceeding row, or decide explicitly which semantics the business actually wants. - Customers with zero orders in the year: they never appear in
salesat all for that year, so they're correctly absent from the result without any extra handling.
Trade-offs and pitfalls
If the business question is genuinely just "whose total for the year exceeds the threshold," a plain GROUP BY customer_id HAVING SUM(amount) > 1000 computes the same customer set with less work: one aggregation pass, no window function, no CTE wrapper, and no risk of the RANGE/ROWS frame trap at all. The window-function-plus-CTE form earns its keep when the question is really about the running value, not just the total: for example, flagging the exact order at which a customer crossed a loyalty threshold, not just whether they crossed it by year-end. Reach for GROUP BY/HAVING when you only need the final number, and reach for the windowed CTE when the row-by-row trajectory itself is part of what's being asked.
You're building analytical features or reports and need row-level detail preserved alongside a group-level aggregate. Give three concrete situations where a window function is the right tool instead of a GROUP BY aggregate, and for each one explain specifically what row-level information a GROUP BY would have thrown away.
Sample Answer
Direct answer: Reach for a window function whenever the downstream consumer needs to see every original row and a group-level or ordered fact attached to it. GROUP BY collapses N rows into one summary row per group, which is correct when you only need the summary, but it permanently discards which specific rows produced that summary, their order relative to each other, and any row that isn't itself the aggregate result. A window function computes the same kind of aggregate or positional fact but writes it back onto every original row instead of replacing them.
Structured elaboration
Situation 1: rolling or trailing time-window features. You need each user-day's trailing 30-day spend as a feature, but you also need to keep the original daily row (date, that day's own spend, any other daily attributes) for model training or a time-series chart. GROUP BY user would collapse all of a user's days into one row and lose the day-by-day granularity entirely; you could GROUP BY user, day, but that just gives you the single day's own spend back, with no way to see the trailing context on that same row.
SELECT user_id, day, amount,
SUM(amount) OVER (PARTITION BY user_id ORDER BY day
ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS spend_30d
FROM transactions;
What GROUP BY would throw away: every day's individual spend value and its position relative to neighboring days; you'd be left with only a single number per user, not a sequence.
Situation 2: row-to-row comparisons (LAG/LEAD). You need the time since a customer's previous transaction, or the previous transaction's amount, as a feature on the current transaction's row.
SELECT *,
LAG(ts) OVER (PARTITION BY user_id ORDER BY ts) AS prev_ts,
ts - LAG(ts) OVER (PARTITION BY user_id ORDER BY ts) AS time_since_prev
FROM events;
What GROUP BY would throw away: there is no group-level aggregate that captures "the specific previous row's value" at all; MIN/MAX/AVG summarize across a whole group, they cannot single out "the one row immediately before this one." GROUP BY has no concept of adjacency between rows.
Situation 3: ranking or flagging within a group, kept at row grain. You need to flag each purchase as a customer's first purchase, or rank each purchase by amount within that customer's history, while keeping every purchase row intact for a transaction log or funnel report.
SELECT *,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY ts) = 1 AS is_first_purchase,
RANK() OVER (PARTITION BY user_id ORDER BY amount DESC) AS amount_rank
FROM purchases;
What GROUP BY would throw away: the identity of which specific row is the first, or how each row ranks against its peers; GROUP BY user_id with MIN(ts) tells you when the first purchase happened but not which purchase row that was or anything else about it (amount, product, channel), because those attributes belonged to a row that GROUP BY has already discarded.
Key points
- The unifying idea: window functions annotate rows, GROUP BY replaces rows with a summary.
- Whenever "I need this detail row, plus some fact computed across its group or neighbors, on the same output row," that's the window-function signal.
- Deduplication and top-N-per-group patterns follow the same shape: rank within a partition, then filter, rather than aggregating the group away.
Worked example
Fixture for events (situation 2's row-to-row comparison):
| user_id | ts |
|---|---|
| 1 | 100 |
| 1 | 130 |
| 1 | 145 |
| 2 | 200 |
| 2 | 260 |
Running the LAG query above against this data (verified in DuckDB):
| user_id | ts | prev_ts | time_since_prev |
|---|---|---|---|
| 1 | 100 | NULL | NULL |
| 1 | 130 | 100 | 30 |
| 1 | 145 | 130 | 15 |
| 2 | 200 | NULL | NULL |
| 2 | 260 | 200 | 60 |
Each user's opening row has no predecessor, so prev_ts and time_since_prev come back NULL; every later row carries the previous row's timestamp and the gap since it, and all five rows stay in the output, rather than being collapsed down to two rows (one per user) the way a GROUP BY user_id would.
Trade-offs & pitfalls
Prefer GROUP BY plus a join back to detail rows over a window function when the aggregate itself is expensive or when only a small number of pre-aggregated values are actually needed downstream (e.g., a small lookup table of category totals used by many queries): materializing the aggregate once and joining is often clearer and cheaper than recomputing a window function over the full detail set every time the query runs. A common wrong turn is reaching for a window function purely out of habit when a true GROUP BY summary was all the report ever needed; that adds unnecessary per-row computation and a wider result set for no benefit.
You've inherited a report that gets each user's latest order via a correlated subquery, and it's slow on a large orders table. Show three ways to get the same result: the original correlated subquery, a derived-table join using MAX(created_at), and a ROW_NUMBER() window function. Explain the performance story for each and when you'd genuinely reach for the correlated form anyway.
Sample Answer
The same "latest order per user" result can be built with a correlated subquery, a derived-table join against a pre-aggregated MAX(created_at), or a ROW_NUMBER() window function; they differ in how much per-row work the engine has to redo and in how they handle ties. On a large orders table, the ROW_NUMBER() form is usually the best default because it computes ranks in one ordered pass and lets you break ties deterministically, but the correlated form is still the right call when the predicate is narrow and well-indexed.
Approach 1: correlated subquery
SELECT o.*
FROM orders o
WHERE o.created_at = (
SELECT MAX(o2.created_at)
FROM orders o2
WHERE o2.user_id = o.user_id
);
Approach 2: derived-table join on MAX(created_at)
SELECT o.*
FROM orders o
JOIN (
SELECT user_id, MAX(created_at) AS max_created
FROM orders
GROUP BY user_id
) m ON o.user_id = m.user_id AND o.created_at = m.max_created;
Approach 3: ROW_NUMBER() window function
SELECT order_id, user_id, amount, created_at
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC, order_id DESC) AS rn
FROM orders o
) t
WHERE rn = 1;
Key points
- Approaches 1 and 2 both compare against
MAX(created_at), so if two orders for the same user share the exact same timestamp, both are returned; neither query has a tiebreaker. - Approach 3 adds
order_id DESCas an explicit tiebreaker, so it always returns exactly one row per user even whencreated_atcollides. ROW_NUMBER()can't be filtered directly in aWHEREclause (window functions evaluate afterWHERE), which is why it has to be wrapped in a subquery, as shown, or filtered withQUALIFYin engines that support it (Snowflake, BigQuery, Databricks; not PostgreSQL or MySQL).
Complexity
The correlated subquery is, logically, one MAX lookup per outer row; whether that's cheap depends entirely on the plan. With an index on (user_id, created_at DESC), a smart optimizer can turn this into an index-descent per user rather than a full re-scan, but many optimizers instead execute it as a nested loop that repeats the inner scan once per outer row, which is the pattern to watch for in EXPLAIN. The derived-table join computes the per-user MAX once, in a single grouped pass over the table (an index or hash aggregate handles this in roughly linear time), then joins that back, which is a bounded amount of work regardless of how many orders a user has. The ROW_NUMBER() form does one sort (or an index-satisfied ordering) per partition, which is generally the same order of work as the grouped aggregate but produces the tiebreaker and the ordering guarantee in the same pass.
Worked example
With five orders across three users, including two orders for user 101 that share the exact same created_at (a same-second data-entry collision), running all three queries against this data shows the difference directly: approaches 1 and 2 both return two rows for user 101 (the tie), while approach 3 with ORDER BY created_at DESC, order_id DESC returns exactly one deterministic row per user, including user 101. (Verified by executing all three queries against SQLite 3.51 with this exact tie case.)
| order_id | user_id | created_at | correlated / derived-join result | ROW_NUMBER() result |
|---|---|---|---|---|
| 2 | 100 | 2024-01-03 09:00:00 | included | included |
| 3 | 101 | 2024-01-02 08:00:00 | included (tie) | excluded |
| 4 | 101 | 2024-01-02 08:00:00 | included (tie) | included (higher order_id wins) |
| 5 | 102 | 2024-01-05 12:00:00 | included | included |
Trade-offs and pitfalls
Genuinely reach for the correlated form when the predicate is highly selective and backed by the right composite index (e.g., you've already filtered down to a handful of users), because a per-row indexed lookup can be cheaper than materializing a full per-user aggregate you don't need elsewhere; some optimizers (PostgreSQL, SQL Server) can automatically rewrite a correlated subquery like this into a semi-join or hash join, but that isn't guaranteed across engines or even across query shapes on the same engine, so don't assume it happened silently. Always check: if EXPLAIN shows a nested loop re-scanning orders once per outer row instead of a hash or merge join, that's the concrete signal to rewrite into the derived-table or ROW_NUMBER() form. The most common bug across all three forms isn't performance, it's silently dropped or duplicated rows from an unhandled tie; if the business logic genuinely needs "the" single latest order, the ROW_NUMBER() form with an explicit tiebreaker is the only one of the three that guarantees it.
First aggregate to the session level (each session's average event value), then apply a second window function across sessions: a 7-session moving average of those per-session averages, ordered by session start, per user. Explain why this needs two separate stages rather than one window function over the raw events.
Sample Answer
Direct answer: Compute this in two separate stages because a "7-session moving average" and a window over raw events are aggregating at two different grains that cannot be collapsed into one window function call. Stage 1 collapses each session down to a single number (its average event value) with a plain GROUP BY. Stage 2 treats those per-session averages as the new rows and applies a ROWS BETWEEN 6 PRECEDING AND CURRENT ROW window, ordered by session start, partitioned by user, to average the last 7 of them. A single window function over the raw events cannot do this because its frame boundary (ROWS, RANGE, or GROUPS, the third and least common frame unit, which counts by peer-group: rows tied on the same ORDER BY value count as one step instead of one row each) always counts something about the current row's grain, rows, values, or peer-groups, and none of those map onto "the last 7 sessions" when the current grain is individual events, not sessions.
Structured elaboration
WITH session_avg AS (
-- Stage 1: collapse events to one row per session
SELECT
s.session_id,
s.user_id,
s.session_start,
AVG(e.event_value) AS avg_event_value_per_session
FROM events e
JOIN sessions s ON e.session_id = s.session_id
GROUP BY s.session_id, s.user_id, s.session_start
)
SELECT
user_id, session_id, session_start, avg_event_value_per_session,
-- Stage 2: window over the session-level rows, not the event-level rows
ROUND(AVG(avg_event_value_per_session) OVER (
PARTITION BY user_id
ORDER BY session_start, session_id
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 4) AS moving_avg_last_7_sessions
FROM session_avg
ORDER BY user_id, session_start, session_id;
Why two stages, concretely: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW counts physical rows in whatever the current FROM clause produces. If that FROM clause is events JOIN sessions, one row per event, then "6 preceding rows" means 6 preceding events, which has nothing to do with 7 sessions unless every session happens to contain exactly one event. A session with 50 events and a session with 2 events contribute wildly different numbers of rows to that frame, so a naive single-stage window silently computes a moving average weighted by how chatty each session was, not an equal-weighted average of 7 session averages, a different, and wrong, metric for the stated question. Collapsing to one row per session in Stage 1 is what makes "7 rows" and "7 sessions" the same thing by the time Stage 2's window runs.
ORDER BY session_start, session_id in both the GROUP BY and the window's ORDER BY matters for the same reason ties matter in any window function: if two sessions for the same user share an identical session_start timestamp, session_id is the deterministic tiebreaker that keeps the window's row order (and therefore which 7 sessions are "the last 7") reproducible across re-runs.
Worked example
Executed against a small sessions(session_id, user_id, session_start) and events(event_id, session_id, event_value) pair: user 1 has 3 sessions. Session 1 (2 events: 10, 20) averages 15. Session 2 (2 events: 30, 50) averages 40. Session 3 (2 events: 5, 15) averages 10. The two-stage query correctly produced a moving average of 15 after session 1 (only one session so far), 27.5 after session 2 ((15+40)/2), and 21.6667 after session 3 ((15+40+10)/3), each is the plain average of all sessions seen so far since fewer than 7 sessions exist yet.
Running a naive single-stage window directly over the joined events/sessions rows, AVG(event_value) OVER (PARTITION BY user_id ORDER BY session_start, session_id ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), on the exact same underlying data produced a different sequence: 10, then 15, then 20, then 27.5, then 23, then 21.6667, one number per event, six numbers total instead of three. None of those six numbers is the "moving average of session averages" the question asked for; the window is silently averaging raw event values in event order, giving sessions with more events more influence over the result purely because they contributed more rows to the frame. This is the concrete, executed proof that the single-stage approach computes a genuinely different, incorrect metric, not just a less elegant version of the right one.
Key points
- A window function's frame counts rows (or a value-range, or peer-groups) at whatever grain the query's
FROMclause currently produces; changing the intended grain requires changing what rows exist first, which is what the Stage 1GROUP BYdoes. - The bug in the single-stage attempt is not a syntax error, the query runs and returns plausible-looking numbers, which is what makes it a dangerous trap rather than an obvious one.
ROUNDis cosmetic; the moving average itself works identically without it, useful to strip out when double-checking exact values against hand-computed expectations.
Complexity
Stage 1 is a straightforward aggregation: a scan of events joined to sessions, grouped by session, O(n) for n events plus the cost of the join. Stage 2 sorts the (much smaller) session-level rows by user_id, session_start, O(m log m) for m sessions, then computes the moving average in a single pass with an incrementally maintained running sum over a fixed 7-row frame, O(m). Because m (sessions) is typically orders of magnitude smaller than n (events), Stage 2 is cheap relative to Stage 1 regardless of table size.
Edge cases
- A user with fewer than 7 sessions total (as in the worked example): the window simply averages however many sessions exist so far,
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWnever demands exactly 7 rows to exist, it caps at 7 but is content with fewer. - A session with zero events: the
JOINin Stage 1 drops it entirely (an inner join), so it never contributes a row tosession_avg; switching to aLEFT JOINand deciding whether a sessionless average should beNULLor0is a deliberate choice, not a default to leave implicit. - Two sessions sharing an identical
session_start: resolved deterministically by thesession_idtiebreaker inORDER BY, without it which session counts as "more recent" in the moving window is undefined and can vary between runs.
Trade-offs & pitfalls
The single-stage version is the trap most candidates walk into under interview pressure because it looks like it should work, PARTITION BY user_id ORDER BY session_start ROWS BETWEEN 6 PRECEDING AND CURRENT ROW reads exactly like "the last 7 things," and the query runs without error. The fix is not a more clever window clause, it is recognizing that the question is really "aggregate, then aggregate the aggregate," which SQL expresses as two window/group stages chained through a CTE (common table expression, a named, reusable subquery introduced with WITH), not one window clause with a cleverer frame. If the requirement changes from "last 7 sessions" to "last 7 calendar days of sessions," Stage 2's frame changes from ROWS BETWEEN 6 PRECEDING to a RANGE BETWEEN INTERVAL '7' DAY PRECEDING on session_start, the two-stage structure itself does not need to change.
A product team wants session-level engagement metrics from raw clickstream events. A session should end after 30 minutes of inactivity, and the same user may generate events from multiple devices. How would you define session boundaries in SQL and compute per-session metrics in a way that is robust to duplicate or out-of-order events?
Sample Answer
Approach
I would define sessions per canonical user ID, not per device, because the requirement says the same user can act from multiple devices. First dedupe duplicate events, then sort by event timestamp, and start a new session when the gap from the previous event is more than 30 minutes.
WITH deduped AS (
SELECT *
FROM (
SELECT
e.*,
ROW_NUMBER() OVER (
PARTITION BY event_id
ORDER BY ingest_ts DESC
) AS rn
FROM clickstream e
) x
WHERE rn = 1
), ordered AS (
SELECT
user_id,
event_ts,
CASE
WHEN LAG(event_ts) OVER (
PARTITION BY user_id
ORDER BY event_ts
) IS NULL
THEN 1
WHEN event_ts - LAG(event_ts) OVER (
PARTITION BY user_id
ORDER BY event_ts
) > INTERVAL '30 minutes'
THEN 1
ELSE 0
END AS new_session
FROM deduped
)
SELECT
user_id,
event_ts,
SUM(new_session) OVER (
PARTITION BY user_id
ORDER BY event_ts
) AS session_id
FROM ordered;
Session metrics
Group by user_id and session_id to get event count, start time, end time, and duration.
Guardrails
Out-of-order events are handled by sorting on event_ts. Duplicates are removed first so they do not create fake activity or split a session.
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.