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.

HardSystem Design
70 practiced

A 12-week retention matrix (one row per signup cohort, one column per week offset, showing percent still active) needs to run nightly against a table of hundreds of millions of users. Beyond just writing the CTE-and-window-function pipeline, propose the performance strategy that makes this feasible: pre-aggregation, partitioning, materialization, or sampling. Then address a related wrinkle: cohort assignment sometimes requires two sequential events (say signup and onboarding-completed) rather than a single timestamp, and events can arrive late and need backfilling without recomputing the whole table.

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
71 practiced

Given a page_views table, write a query to find users who viewed page 'A' and then page 'B' within 10 minutes of each other, using LAG or LEAD to compare consecutive events per user. Then discuss how you'd generalize the same approach to a longer ordered chain, like a 3-step landing-page-to-purchase funnel.

HardTechnical
69 practiced

A finance team wants monthly customer revenue reported against the customer segment that was valid when each order happened, not the segment the customer has today. Some dimension updates arrive late, and some orders are backfilled after the month closes. How would you structure the SQL transformation so the numbers are reproducible, auditable, and easy to reconcile?

HardTechnical
68 practiced

A hierarchy table (employees, categories, or similar) is getting queried with recursive CTEs constantly and it's starting to show up in slow-query logs at millions of rows. Compare recursive CTEs against alternative hierarchical data models (closure table, materialized path, nested sets) for this kind of read-heavy workload: write cost, read cost, and typical maintenance strategy for each, and say which you'd pick 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 Continue

Join thousands of developers preparing for their dream job.