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
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.

HardTechnical
67 practiced

Return the top 3 products per category by revenue, but if there's a tie at the 3rd-place cutoff, include every product tied there (so you might return more than 3 for some categories). Then, separately, walk through a subtler bug: a query is supposed to rank sales by quarterly total, but the ranking gets computed before the quarterly totals are fully aggregated, or a filter gets applied in a way that silently changes which rows the window function sees. Explain the order-of-operations issue and how you'd restructure the query so filtering happens at the right stage.

MediumTechnical
112 practiced

Given a session_events table, write a query that returns each session's first and last event using FIRST_VALUE and LAST_VALUE, being explicit about the frame so LAST_VALUE actually returns the session's true last event. Then discuss when you'd reach for FIRST_VALUE/LAST_VALUE instead of a plain MIN/MAX aggregate, and what changes if you need each customer's first purchase date and the product from that order together in one row.

MediumTechnical
62 practiced

Given an employees table with employee_id, manager_id, and name, write a recursive CTE that returns each employee's full reporting chain up to the top, as a path string like 'CEO > VP > Manager > Employee' along with the depth. Cap the traversal at a reasonable max depth and make sure a bad manager_id cycle in the data can't send it into an infinite loop.

MediumTechnical
79 practiced

Given a table of per-user activity dates (possibly with gaps), write a query that finds each user's streaks of consecutive active days: streak_start, streak_end, and streak_length. Use the classic date-minus-row-number trick (or an equivalent LAG-based approach) and explain why it produces a stable group id for each contiguous run.

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.