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.
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.
Compare a CTE, a derived-table subquery, and a temporary table along one specific axis: scope and persistence. If two separate statements in the same session both need the intermediate result, or if you need it to survive across a transaction boundary, which of the three actually lets you do that, and why do the other two not?
Sample Answer
Direct answer: Only a real temporary table survives past the one statement that defines it. A common table expression (CTE, a named, WITH-clause subquery) and a derived-table subquery are both parsed, planned, and executed as part of a single SQL statement; once that statement finishes, the name is gone and referencing it in a second, separate statement is an undefined-identifier error, transaction or no transaction. A temporary table is a real (if session-scoped) table object: CREATE TEMP TABLE persists across as many later statements as you want in the same session, and by default survives a transaction commit too, because its default lifetime policy is ON COMMIT PRESERVE ROWS.
Structured elaboration
Why a CTE and a subquery are identical on this specific axis: both are query-text constructs, not stored objects. A CTE gives a subquery a name so it can be referenced more than once within the same statement, and may or may not be materialized (engine- and version-dependent), but "materialized" here means "computed once, this statement's execution," not "persisted as a database object." Neither one creates anything that exists a moment after the statement completes. This is why the general readability trade-off between a CTE and an inline derived-table subquery (which is more readable, when nesting gets deep) is a separate question from the one asked here: on scope and persistence, they behave exactly alike.
Why a temp table is different: CREATE TEMPORARY TABLE (or the shorthand CREATE TEMP TABLE) creates an actual table, visible to every subsequent statement in the same database session, with its own storage and (optionally) its own indexes. Two separate statements that both need the same intermediate result can each just query it by name, the same as any other table. Postgres additionally lets you choose what happens to a temp table at commit via an ON COMMIT clause: PRESERVE ROWS (the default: nothing special happens), DELETE ROWS (an automatic TRUNCATE at every commit), or DROP (the table itself is dropped at commit, useful for a genuinely transaction-scoped scratch table). Left at the default, a temp table is the one construct of the three that reliably answers "yes" to both parts of the question: it survives across separate statements in a session, and it survives a transaction boundary.
Worked example (executed in DuckDB)
Statement 1 defines and uses a CTE in one call: WITH doubled AS (SELECT id, val * 2 AS v2 FROM t) SELECT * FROM doubled, which runs fine and returns three rows. Statement 2, a completely separate call that references doubled again with no CTE definition attached, fails immediately: Catalog Error: Table with name doubled does not exist. That's the CTE's statement-scoped lifetime, made concrete. By contrast, CREATE TEMP TABLE doubled_tmp AS SELECT id, val * 2 AS v2 FROM t run as statement 3, followed by SELECT SUM(v2) FROM doubled_tmp as a fully separate statement 4, succeeds and returns the correct aggregate (120), confirming the temp table persisted across the statement boundary that killed the CTE reference outright.
Trade-offs & pitfalls
- Don't reach for a temp table just to "reuse" an intermediate result inside a single statement; a CTE (or even a repeated subquery) already does that without the overhead of creating and later cleaning up a physical table object.
- A temp table needs explicit lifecycle management: an index you might want on it, and eventually a drop (or reliance on session end /
ON COMMIT DROP) to avoid accumulating scratch tables in a long-lived session or connection-pooled application. - "Survives a transaction boundary" is specifically about the table persisting; whether the rows in it survive depends on the
ON COMMIToption chosen at creation, so "temp tables persist across commits" is only true under the default (PRESERVE ROWS), not universally. - This whole comparison is Postgres-flavored; the mechanics of temporary tables (global temp tables, session variables, or engine-specific equivalents) vary enough across SQL Server, MySQL, and Oracle that the general shape (statement-scoped CTE/subquery vs. session-scoped temp object) transfers, but the exact syntax and commit behavior should be checked per engine before relying on it.
Implement Type 2 slowly changing dimension logic: for each business key in a staging table, keep every historical version by effective_date but mark exactly one row per key as current_flag = true. Use a window function to determine which row is current and write the upsert into the dimension table.
Sample Answer
Direct answer: For each business key in the staging table, rank its rows by effective_date descending with ROW_NUMBER() OVER (PARTITION BY custom_key ORDER BY effective_date DESC); the row that lands at rank 1 is the current version. A type 2 slowly changing dimension (a dimension table that keeps every historical version of a record instead of overwriting it, marking exactly one row per key as the current one) needs that current-row determination made once per load and then reconciled against what the dimension table already has: newly-current rows get inserted or flagged, and whatever row was previously flagged current for that key gets its flag cleared if a newer version has arrived.
Structured elaboration
- Rank staging rows per business key.
ROW_NUMBER()partitioned bycustom_key, ordered byeffective_date DESC, gives each row its recency rank within that key; rank 1 is the newest version as of this load. - Derive
current_flagdirectly from the rank, rather than as a separate computed step:rn = 1IS the definition of current. - Reconcile against the existing dimension table. The newly-current row for a key needs
current_flag = TRUEinserted (a genuinely new version) or updated (if it already exists but wasn't flagged current before); any row in the dimension table that WAS flagged current for that key but is no longer the top rank needscurrent_flag = FALSE.
-- staging(custom_key, attr, effective_date)
SELECT custom_key, attr, effective_date,
ROW_NUMBER() OVER (PARTITION BY custom_key ORDER BY effective_date DESC) = 1 AS current_flag
FROM dim_staging;
Worked example (executed in DuckDB). Key 1 has two staging rows (gold effective 2025-01-01, platinum effective 2025-03-01); key 2 has one row (silver effective 2025-02-01).
custom_key | attr | effective_date | current_flag
1 | gold | 2025-01-01 | false
1 | platinum | 2025-03-01 | true
2 | silver | 2025-02-01 | true
Key 1's later row (platinum) is correctly the only one flagged current; the earlier gold row is retained (type 2 keeps history) but demoted. Key 2, with only one row, is trivially current.
Writing the upsert. The insert/update side depends on the engine. Where MERGE is available (SQL Server, Oracle, Snowflake, Postgres 15+), one statement can both insert genuinely new rows and update current_flag on rows that already exist:
MERGE INTO dim_table AS tgt
USING (
SELECT custom_key, attr, effective_date,
ROW_NUMBER() OVER (PARTITION BY custom_key ORDER BY effective_date DESC) = 1 AS current_flag
FROM dim_staging
) AS src
ON tgt.custom_key = src.custom_key AND tgt.effective_date = src.effective_date
WHEN MATCHED THEN
UPDATE SET current_flag = src.current_flag
WHEN NOT MATCHED THEN
INSERT (custom_key, attr, effective_date, current_flag)
VALUES (src.custom_key, src.attr, src.effective_date, src.current_flag);
-- Demote any row for a key that just received a new current version
UPDATE dim_table
SET current_flag = FALSE
WHERE current_flag = TRUE
AND custom_key IN (SELECT custom_key FROM dim_staging)
AND effective_date < (
SELECT MAX(effective_date) FROM dim_staging s WHERE s.custom_key = dim_table.custom_key
);
On engines without MERGE (or where the team prefers explicit control), the same outcome is two statements: an INSERT ... WHERE NOT EXISTS for genuinely new (key, effective_date) combinations, followed by an explicit UPDATE that sets current_flag = FALSE on every previously-current row whose key now has a newer version, and TRUE on the new one.
Trade-offs & pitfalls
- Late-arriving data (a row with an
effective_dateearlier than the current dimension row, but arriving after the load that made that row current) needs its own handling: naively re-running the rank-and-flag logic against the union of staging and existing dimension rows, not staging alone, is what correctly re-derives which row is current after a backdated insert. - A tie on
effective_datefor the same key needs a secondaryORDER BYkey (a load sequence number or ingestion timestamp), or which of two same-day versions ends up flagged current is the identical nondeterminism problem covered under dedup tie-breaking elsewhere in this topic. RANK()instead ofROW_NUMBER()would let two rows share rank 1 on an exact effective-date tie, which almost never matches the type 2 requirement of exactly one current row per key; useROW_NUMBER()specifically, notRANK(), for this pattern.- Don't forget an
effective_end_date(or equivalent) column alongsidecurrent_flag: setting the previous row's end date to the new row's effective date at demotion time is what makes point-in-time historical queries ('what did this record look like on date X') possible, not just 'what is it now.'
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.
You want to check whether related rows exist in another table without duplicating the left-hand rows the way a plain JOIN can. Using orders and payments, show when you'd reach for EXISTS instead of a JOIN specifically to avoid row duplication (not for the NULL-handling reason), with an example where the JOIN version silently multiplies rows.
Sample Answer
Direct answer: Reach for EXISTS instead of a JOIN when you only need to know whether a related row exists and you do not want the left table's rows duplicated by the join. A LEFT JOIN (or INNER JOIN) produces one output row per matching right-side row, so an order with three payment rows shows up three times; EXISTS returns a single boolean per order and never multiplies anything, because it only asks "is there at least one match," not "give me every match." This is a separate problem from the NOT IN / NULL trap: it is about row multiplication from the join's cardinality, not about NULLs breaking a comparison.
Structured elaboration
- A
JOIN's output cardinality is driven by how many rows on the right side match each row on the left. Ifpayments.order_idis not unique per order,orders JOIN paymentsreturns one row per (order, payment) pair, not one row per order. EXISTSis a correlated subquery that the engine evaluates as true/false per outer row; it stops at the first matching payment and never expands the result set.- If all you need is a flag ("does this order have a payment yet") or you're filtering on existence (
WHERE EXISTS (...)),EXISTSis both correct and typically cheaper, because it doesn't have to materialize every matching payment row just to throw most of them away. - If you genuinely need columns FROM the right table (e.g. the payment amount), you cannot avoid a JOIN, but you can avoid duplication by picking exactly one right-side row per left-side row first (a
ROW_NUMBER()filtered to 1, or an aggregate likeMAX(amount)), then joining to that pre-reduced result instead of the raw table.
Worked example (executed in DuckDB)
-- orders(id, user_id, total); payments(id, order_id, amount)
CREATE TABLE orders (id INT, user_id INT, total INT);
INSERT INTO orders VALUES (100, 123, 50);
CREATE TABLE payments (id INT, order_id INT, amount INT);
INSERT INTO payments VALUES (1,100,20), (2,100,20), (3,100,10); -- three partial payments on the same order
-- LEFT JOIN: one order silently becomes three rows
SELECT o.id AS order_id, o.total, p.id AS payment_id
FROM orders o
LEFT JOIN payments p ON p.order_id = o.id
WHERE o.user_id = 123;
-- -> (100,50,1), (100,50,2), (100,50,3) -- the order row is tripled
-- EXISTS: exactly one row, no duplication
SELECT o.id AS order_id, o.total,
EXISTS (SELECT 1 FROM payments p WHERE p.order_id = o.id) AS has_payment
FROM orders o
WHERE o.user_id = 123;
-- -> (100, 50, true) -- one row, as expected for one order
If this order feeds a report that sums total per user, the LEFT JOIN version overstates that user's order total by 3x purely because of how many payments happened to exist, which is a subtle and easy-to-miss bug: the query runs fine, returns real-looking data, and the error only shows up as an inflated aggregate somewhere downstream.
Trade-offs & pitfalls
- The fix is not always "use EXISTS everywhere": if you need
payments.amountin the output, EXISTS can't give it to you, and a JOIN is genuinely required. In that case dedupe first (pick the latest or largest payment per order) rather than joining raw. COUNT(*)after a JOIN is a common place this bug hides:SELECT COUNT(*) FROM orders o JOIN payments p ON ...counts payments, not orders, if you meant the latter.- Don't reach for
DISTINCTas a band-aid over row multiplication; it's slower than not creating the duplicates in the first place, and it silently hides which rows are getting deduped and why.
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.