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

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.

MediumTechnical
70 practiced

Given a users table with first_activity_date and last_activity_date, write a query that produces one row per user per calendar day between those two dates (filling in zero-count days where no events exist), suitable as the base for a sliding-window feature computation. Show it once with a recursive CTE and note the non-recursive generate_series-style alternative most engines support.

MediumTechnical
82 practiced

You are given an event table with one row per order and irregular timestamps. A product manager wants a rolling 7-day order count per store, but analysts disagree on whether that means the previous 168 hours or the current day plus the previous 6 calendar days. How would you clarify the requirement and implement the query so boundary cases are unambiguous?

HardTechnical
71 practiced

Build a paginated leaderboard where tied scores share the same rank, but pagination still has to return consistent, non-overlapping pages even when a tie spans a page boundary. Explain the pagination strategy you'd use and why naive OFFSET/LIMIT breaks down here.

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.