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.
For a new KPI calculation that will be reused across multiple dashboards, decide between a CTE, a temporary/staging table, and a materialized view. What criteria drive the decision (readability, reuse, performance, indexability, freshness, transactional behavior), and how does your answer differ for: a one-off ad hoc analysis, a repeatedly-used expensive calculation, and a near-real-time dashboard?
Sample Answer
Direct answer: Pick the tool by matching its physical behavior to what the KPI (key performance indicator) actually needs: a common table expression (CTE, a named subquery written with WITH ... AS (...)) for a one-off analysis you'll run once and throw away, a temp or staging table when the calculation is expensive but the reuse window is short (a single session, a single ETL run, meaning extract-transform-load), and a materialized view (a query whose result is physically stored on disk and refreshed on a schedule or trigger, rather than recomputed on every read) once the same expensive logic is read repeatedly by multiple dashboards and can tolerate being slightly stale. Near-real-time dashboards are the one case where none of the "precompute it" options fit cleanly: they usually need a lean, indexable live query instead, or an incrementally-updated summary table rather than a full materialization.
Structured elaboration
| Criterion | CTE | Temp / staging table | Materialized view |
|---|---|---|---|
| Readability | High: named, inline, keeps logic next to the query that uses it | Medium: logic is split across a create step and a query step | High for consumers: they just query it like any table; the transformation logic lives elsewhere |
| Reuse across queries/dashboards | None by default: re-declared and recomputed in every query that needs it (Postgres 12+ inlines a single-reference CTE by the query planner) | Good within one session or job; not visible to other sessions unless persisted | Best: one physical object every dashboard can SELECT from |
| Performance (recompute cost) | Recomputed every time the query runs; cheap for small inputs, expensive if reused often on a large base table | Computed once per session/job; indexable afterward | Computed once per refresh cycle; reads are just a table scan |
| Indexability | None: a CTE has no persistent structure to index | Yes: you can add indexes to a temp table after loading it | Yes: materialized views can carry their own indexes in most engines |
| Freshness | Always current as of the moment the query runs | Current as of whenever it was populated in that session/job | Only as current as the last refresh; staleness is a designed trade-off, not a bug |
| Transactional behavior | Part of the surrounding transaction; nothing persists beyond the query | Local to a session/connection (or transaction, depending on TEMPORARY/##temp semantics); dropped automatically | A separate persisted object with its own refresh transaction, decoupled from any one query's transaction |
Recommendations by scenario:
- One-off ad hoc analysis: a CTE (or a plain subquery). There is no second reader to amortize setup cost against, so the fastest path to an answer wins over any persistence machinery.
- Repeatedly-used expensive calculation: a materialized view (or, where the engine lacks native materialized views, a scheduled job that populates a plain table). The cost of computing it is paid once per refresh instead of once per dashboard load, and it becomes indexable, which a CTE never is.
- Near-real-time dashboard: avoid full materialization; either query the base tables directly with supporting indexes so the planner can push filters down, or maintain an incrementally-updated summary table (updated on write, not recomputed wholesale) if the underlying computation is too heavy to run live on every page load.
When does a CTE pipeline graduate to a materialized view? Three independent signals, any one of which is usually enough on its own: (1) reuse -- the same CTE logic is being copy-pasted into a second, third, or fourth query or dashboard, which is a sign the definition should live in one place instead of many; (2) performance -- the CTE's underlying computation starts showing up as the dominant cost in an EXPLAIN plan across multiple callers, so the aggregate cost of recomputing it everywhere now exceeds the cost of maintaining a refreshed copy; (3) governance -- different query authors start writing slightly different filters around a copy-pasted CTE, so the "same" KPI silently drifts between dashboards. Any of these is the point to promote the logic into a materialized view (or persisted table) with one refresh schedule and one definition that every consumer reads.
Worked example
A KPI like "monthly active accounts" (distinct accounts with at least one qualifying event in the trailing 30 days) is a good stand-in: it is expensive on a large events table because it needs a distinct count over a rolling window, and it is exactly the kind of metric multiple dashboards want to show.
-- (a) one-off exploration: CTE, thrown away after this single query
WITH active_accounts AS (
SELECT DISTINCT account_id
FROM events
WHERE event_time >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT COUNT(*) AS mau FROM active_accounts;
-- (b) repeatedly-used, refresh-tolerant: materialized view, indexed, refreshed nightly
CREATE MATERIALIZED VIEW mv_monthly_active_accounts AS
SELECT account_id, MAX(event_time) AS last_active_at
FROM events
WHERE event_time >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY account_id;
CREATE INDEX idx_mv_maa_account ON mv_monthly_active_accounts(account_id);
-- refreshed on a schedule, e.g. REFRESH MATERIALIZED VIEW mv_monthly_active_accounts;
-- (c) near-real-time: query live, relying on an index on events(account_id, event_time)
-- rather than pre-aggregating, so results are current to the second
SELECT COUNT(DISTINCT account_id) AS mau_live
FROM events
WHERE event_time >= NOW() - INTERVAL '30 days';
ML (machine learning) feature pipeline framing: this exact decision tree also applies when the "dashboard" is actually a model training job reading a feature. A feature explored once in a notebook is a CTE; a feature reused across many training runs (and needing point-in-time correctness, i.e. only using data available as of each label's timestamp) is exactly the "repeatedly-used expensive calculation" case, and belongs in a materialized feature table (or a feature store) that is refreshed on a known cadence, not recomputed inline in every training query. The freshness criterion becomes sharper here: a stale feature table used for training is often fine, but the same staleness at serving/inference time can silently create training-serving skew, so the acceptable staleness window has to be decided per use case, not assumed.
Spark SQL / Catalyst optimizer angle: the reuse math is different in Spark. Spark's Catalyst optimizer treats a WITH clause referenced multiple times by inlining and re-planning the underlying logical plan at each reference site by default, rather than computing it once and sharing the result the way a materialized view would. A CTE joined against three times in one Spark SQL query can trigger the same expensive computation three separate times unless you explicitly force sharing (persisting the intermediate DataFrame with .cache()/.persist(), or writing it out and reading it back). This makes the "graduate to materialization" decision arrive sooner in Spark than in a single-node warehouse: a CTE reused even twice within one query is worth checking for repeated work, not just a CTE reused across many separate queries.
Trade-offs & pitfalls
The common wrong turn is reaching for a materialized view purely because a query is slow, without checking whether the consumer can actually tolerate the staleness that comes with it: a materialized view refreshed hourly is the wrong answer for a dashboard that promises "as of right now." Conversely, leaving an expensive, frequently-reused CTE unmaterialized "for simplicity" quietly multiplies its cost by however many dashboards call it, since nothing about a CTE shares work across separate queries. Temp/staging tables sit in between and are easy to over- or under-use: they are the right tool inside a single multi-step job (build once, query several times, then discard), but reaching for one to serve a dashboard means re-inventing a materialized view's refresh logic by hand, usually worse. Always confirm the actual freshness requirement with the stakeholder before choosing: "near-real-time" and "updated every 15 minutes" are very different engineering problems that get conflated in casual requirements language.
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.
Given a session_events table, write a query that returns each session's first and last event using FIRST_VALUE and LAST_VALUE, being explicit about the frame so LAST_VALUE actually returns the session's true last event. Then discuss when you'd reach for FIRST_VALUE/LAST_VALUE instead of a plain MIN/MAX aggregate, and what changes if you need each customer's first purchase date and the product from that order together in one row.
Sample Answer
Direct answer
Partition by session_id, order by event_time, and give LAST_VALUE an explicit ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING frame so it returns the session's true last event instead of just echoing the current row. Left implicit, an ORDER BY with no frame clause defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: for any given row, that frame's upper edge stops at the row itself, so the window has not yet seen any of the rows that come after it in the session. LAST_VALUE can only return the last value inside the frame it is given, and on every row the frame ends at that row, which is why it echoes the current event instead of the session's true last one (the same default-frame trap that affects any window aggregate that relies on LAST_VALUE). Wrap the result in SELECT DISTINCT (or aggregate it afterward) to collapse the per-event output down to one row per session. Reach for FIRST_VALUE/LAST_VALUE instead of a plain MIN/MAX specifically when you need another column's value from the same row as the minimum or maximum, since MIN/MAX alone only give you the extreme value of the aggregated column itself, not the rest of that row.
Structured elaboration
- Window-function version:
FIRST_VALUE/LAST_VALUEwithPARTITION BY session_id ORDER BY event_timeand the widened frame, thenSELECT DISTINCT session_id, ...to fold the many event rows per session down to one output row per session. - Why not just
MIN(event_time)/MAX(event_time):MIN(event_time)tells you the earliest timestamp in the session, but nothing about whichevent_namehappened at that timestamp; getting that co-located column otherwise requires a self-join or correlated subquery back to the original table.FIRST_VALUE(event_name) OVER (... ORDER BY event_time)gets both the extreme value and any other column from that same row in a single pass. - Same idea applied to "each customer's first purchase date and the product from that order together":
FIRST_VALUE(order_date)andFIRST_VALUE(product), both windowed the same way (PARTITION BY customer_id ORDER BY order_date), pull the date and the product from the same first order in one query, which a plainMIN(order_date)cannot do on its own.
Worked example
SELECT DISTINCT
session_id,
FIRST_VALUE(event_name) OVER (PARTITION BY session_id ORDER BY event_time
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS first_event,
FIRST_VALUE(event_time) OVER (PARTITION BY session_id ORDER BY event_time
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS first_event_time,
LAST_VALUE(event_name) OVER (PARTITION BY session_id ORDER BY event_time
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_event,
LAST_VALUE(event_time) OVER (PARTITION BY session_id ORDER BY event_time
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_event_time
FROM session_events;
Executed against two sessions: session s1 has three events (page_view at 10:00, add_to_cart at 10:02, checkout at 10:05), giving first_event = page_view at 10:00 and last_event = checkout at 10:05. Session s2 has two events, both named page_view (at 11:00 and 11:01), giving first_event = last_event = page_view, but with distinct first_event_time = 11:00 and last_event_time = 11:01, confirming the query correctly distinguishes "same event name" from "same event time."
The first-purchase-plus-product variant, executed against orders(customer_id, order_date, product) with customer 1's earliest order on Jan 1 for a Widget (a later order on Jan 10 for a Gadget) and customer 2's single order on Feb 1 for a Gizmo, correctly returns (1, 2024-01-01, Widget) and (2, 2024-02-01, Gizmo).
Complexity
Getting first/last event per session needs each session's rows sorted by event_time first: O(n log n) without an index on (session_id, event_time), O(n) with one. Because the frame is UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, the engine has to hold each session's full row set before it can emit LAST_VALUE for any row in that session, unlike a CURRENT ROW-bounded running total that can stream through a partition incrementally; a session with an unusually large number of events raises memory pressure and spill risk for that one partition specifically. The SELECT DISTINCT on top is an extra dedup pass over the (already one-row-per-original-event) output, cheap relative to the sort, but still a second full pass over the data, not free.
Trade-offs & pitfalls
- An alternative worth naming:
ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY event_time) = 1(and a mirroredDESCversion for the last row), then filter to that row directly. It is more verbose for one or two columns, but clearer and less repetitive thanFIRST_VALUE/LAST_VALUEonce you need many columns from the same first or last row, since aROW_NUMBERfilter lets youSELECT *instead of repeating the sameOVERclause for every column. - Ties on
event_timeneed a documented tie-breaker (anevent_id); without one, which specific tied row's other columnsFIRST_VALUE/LAST_VALUEreturn is not guaranteed to be consistent across runs. SELECT DISTINCTover window-function output can hide a broken frame rather than surfacing it: if the frame is left at its buggy default,DISTINCTwill simply return one row per original event instead of one row per session (no error, just a wrong-shaped result), so validate that the output row count actually equals the number of distinct sessions as a sanity check, rather than trusting that the query ran without errors.
Compute percent change versus the same period one year ago using a multi-step LAG offset (for example LAG(value, 365)), and discuss what goes wrong around leap years. Then handle the harder version: comparing to the same weekday last year rather than the same calendar date, so a Monday compares to a Monday.
Sample Answer
Direct answer
LAG(value, 365) assumes the row exactly 365 positions back is "the same calendar date one year ago." That assumption only holds if every day has exactly one row and no leap day falls inside the twelve months between the two rows; once a February 29 sits in that span, the 365-row offset lands one calendar day early. The fix is to stop counting rows and instead join the table to itself on date - INTERVAL '1 year', which tracks the calendar directly. A second, independent problem is that "the same calendar date last year" is not "the same day of the week": a Monday this year usually is not a Monday on the same numeric date last year, which matters for anything with weekly seasonality (retail traffic, weekday-vs-weekend patterns). Fixing that requires aligning on the ISO week (the ISO 8601 standard's week-numbering scheme, where every week runs Monday through Sunday) and weekday, not on the calendar date.
Structured elaboration
Why the row offset breaks: LAG(x, 365) is positional, not date-aware. Executed directly: DATE '2024-03-01' - INTERVAL 365 DAY returns 2023-03-02, one day later than the true "same date last year" (2023-03-01), because 2024 is a leap year and the twelve months between those two dates contain 366 days, not 365. DATE '2024-03-01' - INTERVAL 1 YEAR correctly returns 2023-03-01 because interval-year arithmetic follows the calendar, not a fixed day count.
Fix 1, calendar-date join:
SELECT
cur.store_id, cur.sale_date, cur.total_sales,
prev.total_sales AS total_sales_last_year,
CASE WHEN prev.total_sales IS NULL THEN NULL
ELSE ROUND((cur.total_sales - prev.total_sales)::numeric / prev.total_sales * 100, 2)
END AS pct_change_yoy
FROM daily_sales cur
LEFT JOIN daily_sales prev
ON prev.store_id = cur.store_id
AND prev.sale_date = cur.sale_date - INTERVAL '1 year';
February 29 has no "same calendar date" last year at all; decide explicitly whether it maps to February 28 or March 1 in the join (a CASE on the anchor date), and document the choice, because either is defensible and silent inconsistency between reports is worse than either choice alone.
Fix 2, weekday alignment: two workable techniques, with different trade-offs.
- A fixed 364-day (52-week) offset guarantees an exact day-of-week match, because 364 = 52 × 7. Executed:
DATE '2024-03-04' - INTERVAL 364 DAYreturns2023-03-06, and both2024-03-04and2023-03-06are Mondays. The cost is that 364 days is not a full calendar year, so across several years the "last year" comparison date drifts away from the true anniversary date by roughly one to two days per year. - An exact join on
(ISO year - 1, ISO week, ISO weekday)anchors to the actual week structure instead of a fixed day count. Executed against two rows (2023-03-06, a Monday in ISO week 10 of 2023;2024-03-04, a Monday in ISO week 10 of 2024): joining onisoyear(prev) = isoyear(cur) - 1 AND weekofyear(prev) = weekofyear(cur) AND isodow(prev) = isodow(cur)correctly matches the two Mondays.
Worked example
Naive calendar-date weekday check: 2024-03-04 is a Monday; the naive "same date last year," 2024-03-04 - INTERVAL 1 YEAR = 2023-03-04, is a Saturday. A week-over-week or day-of-week-sensitive comparison using the naive join would be comparing a Monday's traffic to a Saturday's traffic and drawing a conclusion about "year-over-year growth" that is really a day-of-week artifact.
Trade-offs & pitfalls
- The fixed-365-row offset is the cheapest to write and looks correct on data that happens not to cross a leap day during testing, which is exactly how this bug ships silently.
- The calendar-date self-join needs an index on
(store_id, sale_date)to stay cheap; without one, the self-join becomes an expensive full scan on both sides. - The 364-day weekday-alignment offset is simple but not exact over multiple years; if you need the comparison to stay a true anniversary AND stay on the same weekday indefinitely, only the ISO year/week/weekday join does both correctly.
- ISO week numbering follows the Gregorian calendar's own week structure; a business running a genuinely different fiscal calendar (e.g. 4-4-5 retail calendars) needs to join on that calendar's own week definition, not ISO weeks, or the "same week" comparison is still wrong despite looking fixed.
Given a table of per-user activity dates (possibly with gaps), write a query that finds each user's streaks of consecutive active days: streak_start, streak_end, and streak_length. Use the classic date-minus-row-number trick (or an equivalent LAG-based approach) and explain why it produces a stable group id for each contiguous run.
Sample Answer
Direct answer: For each user, number the activity dates in order with ROW_NUMBER(), then subtract that row number (in days) from the actual date. Within one unbroken run of consecutive days, the date increases by exactly 1 each row while the row number also increases by exactly 1, so date - row_number is a constant for the entire run and jumps to a new constant the moment there's a gap. That constant is a ready-made, stable group id: group by it (per user) and aggregate to get each streak's start, end, and length.
Structured elaboration
Why the trick works, concretely. If a user is active on Jan 1, 2, 3 (three consecutive days), their row numbers are 1, 2, 3. date - row_number, expressed as date - (row_number * INTERVAL 1 day) so both sides are dates, gives Dec 31, Dec 31, Dec 31 for all three rows: the row number is climbing at exactly the same rate as the date, so the difference is invariant. The moment there's a gap (say the next activity is Jan 5, skipping Jan 4), the row number continues climbing by 1 (to 4) but the date jumps by 2, so date - row_number shifts to a new constant. Every row in a contiguous run shares one constant; every gap produces a new constant. That is why grouping by this value is safe and deterministic, unlike an arbitrary running counter that would need a separate flag-and-cumsum step (the LAG-based alternative below does exactly that instead).
WITH numbered AS (
SELECT user_id, activity_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY activity_date) AS rn
FROM activity
),
grouped AS (
SELECT user_id, activity_date,
activity_date - (rn * INTERVAL '1 day') AS island_id
FROM numbered
)
SELECT user_id, island_id,
MIN(activity_date) AS streak_start, MAX(activity_date) AS streak_end, COUNT(*) AS streak_length
FROM grouped
GROUP BY user_id, island_id
ORDER BY user_id, streak_start;
LAG-based equivalent. Instead of arithmetic on the date, compare each row directly to the previous one: flag a new streak whenever activity_date <> prev_date + 1, then take a running SUM of that flag as the group id. This produces the identical grouping, at the cost of one extra window pass; it generalizes more naturally when the gap rule is not a fixed "+1 day" (see below).
Worked example (executed in DuckDB). User 1's activity dates: Jan 1, 2, 3 (a 3-day streak), then Jan 5, 6 (a 2-day streak after a 1-day gap), then Jan 10 (an isolated day).
user_id | streak_start | streak_end | streak_length
1 | 2025-01-01 | 2025-01-03 | 3
1 | 2025-01-05 | 2025-01-06 | 2
1 | 2025-01-10 | 2025-01-10 | 1
The island_id values produced internally were three distinct dates (one per run), confirming the arithmetic correctly separated the three streaks without any explicit gap-detection logic.
Generalizing the same island logic
- Coarser granularity (3+ consecutive weeks). Replace "day" with "week": truncate each activity date to its week start (e.g.
date_trunc('week', activity_date)), dedupe to one row per (user, week), then apply the identicaldate - row_numbertrick usingINTERVAL '1 week'instead of'1 day'. The mechanism is unchanged; only the unit of contiguity changes. - A per-user variable gap threshold. If "consecutive" means something other than a fixed 1-day gap per user (e.g. some users are only expected to be active every other day), the date-minus-row-number arithmetic trick stops applying cleanly, because it depends on the gap being a fixed, known constant. Switch to the LAG-based form and compare against a per-user threshold column instead of a literal
+ 1:CASE WHEN activity_date > prev_date + gap_threshold THEN 1 ELSE 0 END. - A tolerance window on the contiguity test. If a single missed day should still count as "the same streak" (a grace-day rule), change the LAG comparison from
<> prev_date + 1to> prev_date + tolerance_days, i.e. only break the streak when the gap exceeds the tolerance, not on any gap at all. - The same pattern on a non-boolean series. The identical island logic applies to "3+ consecutive days of declining revenue" or "consecutive growing-revenue days": instead of flagging by date contiguity, flag each row by
CASE WHEN revenue < LAG(revenue) OVER (...) THEN 1 ELSE 0 END(a direction change breaks the streak) and take the running SUM of direction-changes as the group id. The grouping mechanism (a monotonically non-decreasing counter that only increments at a boundary) is exactly the same; only the definition of "boundary" changes.
Trade-offs & pitfalls
- Deduplicate same-day activity before ranking (
GROUP BY user_id, activity_datefirst); otherwise a duplicate row inflatesstreak_lengthwithout representing a real extra day. - The date-minus-row-number trick specifically needs a fixed, known step size (1 day, 1 week); once the gap rule is conditional or per-user, fall back to the LAG-and-cumulative-sum form, which handles any boundary condition you can express as a boolean.
date - row_numberonly produces a stable id within one user's partition; always includeuser_idin the finalGROUP BY, or two different users' unrelated streaks that happen to land on the same constant will merge.
Unlock Full Question Bank
Get access to all 47 Advanced SQL: Window Functions, CTEs, and Subqueries interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.