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

Compute a running total per user and add a boolean column that flips to true the first time the running total crosses a fixed threshold (say 10,000) for that user. Explain how you handle ties on the order-by timestamp and NULL amounts so the flag doesn't flicker on and off.

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.

MediumTechnical
66 practiced

Finance wants a month-to-date revenue trend by product from a daily sales fact table, but some product-day combinations are missing because there were no sales. The report still needs to show zero-revenue days and reset correctly at each month boundary. How would you structure the query and what reference data, if any, would you need?

HardTechnical
63 practiced

Two large tables A and B: you need to check whether a row in A has any matching row in B, without duplicating A's rows and without a huge WHERE id IN (subquery) blowing up. Compare EXISTS/NOT EXISTS against LEFT JOIN ... IS NULL for this, and discuss how duplicates in B and indexing choices change which one is actually faster.

MediumTechnical
78 practiced

You're building analytical features or reports and need row-level detail preserved alongside a group-level aggregate. Give three concrete situations where a window function is the right tool instead of a GROUP BY aggregate, and for each one explain specifically what row-level information a GROUP BY would have thrown away.

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.