InterviewStack.io LogoInterviewStack.io

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.

MediumTechnical
60 practiced

Compute the day-over-day (or week-over-week) percent change in a metric using LAG. Handle the case where the previous period's value is NULL (no prior data) or zero (to avoid a divide-by-zero error), and show how the same LAG-based idea can convert a table that only stores cumulative balances into daily deltas.

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.

HardTechnical
74 practiced

Given a bill-of-materials table (parent_id, child_id, qty) and a component cost table, write a recursive CTE that rolls up the total cost of a top-level product by multiplying and summing costs down through the component tree. Handle cycle detection so a bad parent/child link can't cause infinite recursion, and discuss how the query holds up as the tree gets deep.

MediumTechnical
63 practiced

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.

MediumTechnical
69 practiced

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.

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.