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.
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?
An executive dashboard needs the top 3 products by revenue in each region. If multiple products tie at the cutoff, every tied product must appear, but revenue should be computed from raw line items without double counting order-level facts. How would you build the query so the aggregation and ranking both stay correct?
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?
An app team wants to find each user's longest streak of consecutive active days, and also return the start date, end date, and streak length. Multiple events can occur on the same day, and some users have gaps caused by missing source data. How would you solve this in SQL, and how would you guard against counting bad data as broken streaks?
A query that used to run in seconds now takes minutes after a rewrite into several CTEs for readability. The result is still correct, but the warehouse scan shows repeated work on the same large tables. How would you investigate whether the CTE structure is helping or hurting, and what would you change first if the execution plan looks suspicious?
Unlock Full Question Bank
Get access to all 10 Advanced SQL: Window Functions, CTEs, and Subqueries interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.