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.

HardTechnical
74 practiced

Given a bill-of-materials table (parent_id, child_id, qty) and a component cost table, write a recursive CTE that rolls up the total cost of a top-level product by multiplying and summing costs down through the component tree. Handle cycle detection so a bad parent/child link can't cause infinite recursion, and discuss how the query holds up as the tree gets deep.

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.

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.

EasyTechnical
64 practiced

Explain what makes a subquery correlated versus non-correlated, and why a correlated subquery conceptually re-runs once per outer row. Using an employees(emp_id, department_id, salary) table, write a correlated subquery that returns each employee's salary next to their department's average salary, and contrast it with a non-correlated subquery for a different, single-value comparison.

HardTechnical
124 practiced

You're about to ship a recursive CTE as part of a production pipeline (for example, computing a time-decayed or exponentially weighted running value per row, where each row's result depends on the previous row's computed result). List the concrete guardrails you'd put in place before deploying it (recursion depth caps, cycle protection, timeouts), and explain why an ordinary window function can't express this kind of row-depends-on-previous-row recurrence directly.

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.