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.

HardTechnical
59 practiced

You need to remove duplicate rows from a large production table (hundreds of millions of rows) while minimizing lock contention and write downtime. Compare at least two approaches (for example: a windowed DELETE in batches, versus building a deduplicated copy and swapping it in) and discuss backup, transaction, and rollback considerations for each.

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

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.

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.