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.

HardTechnical
59 practiced

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.

MediumTechnical
74 practiced

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.

HardTechnical
104 practiced

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?

HardTechnical
78 practiced

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.

EasyTechnical
64 practiced

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?

Unlock Full Question Bank

Get access to all Advanced SQL: Window Functions, CTEs, and Subqueries interview questions and detailed answers.

Sign in to Continue

Join thousands of developers preparing for their dream job.