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
62 practiced

For a new KPI calculation that will be reused across multiple dashboards, decide between a CTE, a temporary/staging table, and a materialized view. What criteria drive the decision (readability, reuse, performance, indexability, freshness, transactional behavior), and how does your answer differ for: a one-off ad hoc analysis, a repeatedly-used expensive calculation, and a near-real-time dashboard?

HardTechnical
104 practiced

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?

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.

HardTechnical
56 practiced

Compute percent change versus the same period one year ago using a multi-step LAG offset (for example LAG(value, 365)), and discuss what goes wrong around leap years. Then handle the harder version: comparing to the same weekday last year rather than the same calendar date, so a Monday compares to a Monday.

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.