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

Define a user as churned if they had activity in month N but no activity in months N+1 and N+2, and build a monthly churn_rate table from an events log using this rule. Then adapt the same logic to generate churn labels for a supervised model (one label per anchor date per user), making sure the query never looks at data after the anchor date when deciding the label.

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?

HardTechnical
79 practiced

A correlated subquery in a WHERE clause is quietly returning wrong totals because the table it correlates against has duplicate rows for the join key. Walk through why this happens and show two ways to fix it: DISTINCT inside the subquery, and rewriting as a GROUP BY plus JOIN.

MediumTechnical
77 practiced

An executive dashboard needs the top 3 products by revenue in each region. If multiple products tie at the cutoff, every tied product must appear, but revenue should be computed from raw line items without double counting order-level facts. How would you build the query so the aggregation and ranking both stay correct?

MediumTechnical
101 practiced

You've inherited a report that gets each user's latest order via a correlated subquery, and it's slow on a large orders table. Show three ways to get the same result: the original correlated subquery, a derived-table join using MAX(created_at), and a ROW_NUMBER() window function. Explain the performance story for each and when you'd genuinely reach for the correlated form anyway.

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.