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.

EasyTechnical
76 practiced

Your orders table can contain multiple rows per customer because of updates and replays. A downstream report needs exactly one row per customer: the most recent order, and if two rows share the same timestamp the choice must be deterministic. How would you write the SQL, and how would you adjust it if the business later asks to keep every row tied for the latest timestamp?

MediumTechnical
70 practiced

Write a query for a user's top 3 orders by amount two ways: filtering a ROW_NUMBER() result in an outer query, and using a LATERAL join with LIMIT. Discuss the readability and performance trade-offs on a warehouse with millions of users, and how your answer changes if the 'N' in top-N needs to vary per group instead of being a fixed constant.

HardTechnical
65 practiced

Compute the median (50th percentile) of a numeric column using PERCENTILE_CONT, or a manual NTILE/ROW_NUMBER-based workaround in a dialect that lacks it. Then discuss when you'd switch to an approximate method (sketch-based quantile estimation, or an engine's built-in approximate-quantile function) instead of the exact windowed computation, and how you'd communicate that trade-off to a stakeholder who just wants 'the median'. Extend the same exact-versus-approximate framing to a related problem: an exact running-distinct-count of active users by day gets expensive at scale, and HyperLogLog-style sketches are the usual approximate alternative.

HardTechnical
62 practiced

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?

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.

Unlock Full Question Bank

Get access to all 47 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.