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

Given a table of user events with a timestamp, write a query that assigns a session_id per user, where a new session starts whenever the gap since the previous event for that user exceeds 30 minutes. Return session_start, session_end, and event_count per session, and explain how your approach would need to change for events crossing device boundaries or spanning multiple time zones.

HardTechnical
80 practiced

Given a login-attempts table, write a query that flags users with 3 or more consecutive failed login attempts within any rolling 10-minute window, returning the user and the start time of the offending sequence. Explain how you avoid both false positives (isolated failures spread far apart) and firing duplicate alerts for the same overlapping sequence.

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

When deduplicating rows by picking the 'best' one per group with ROW_NUMBER, two rows can have identical values on every column in your ORDER BY, including the timestamp. Explain how this breaks the determinism of the result and propose a tie-breaking strategy (multiple ORDER BY keys, a priority ranking, or similar) that makes the query idempotent across repeated runs.

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?

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.