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

Your team owns a daily leaderboard built from a fact table with billions of rows. The query uses several window calculations over partitions by customer, country, and day, and it starts spilling to disk during peak load. What would you look at to tune it without changing the business result?

HardTechnical
69 practiced

You inherit a parent-child category table for a product catalog. The business needs each category's full ancestor path, its depth in the hierarchy, and a safe rollup of sales to all ancestors. Some records are malformed and create cycles or orphan nodes. How would you query this with a recursive CTE while protecting the warehouse from runaway recursion?

HardTechnical
70 practiced

Implement Type 2 slowly changing dimension logic: for each business key in a staging table, keep every historical version by effective_date but mark exactly one row per key as current_flag = true. Use a window function to determine which row is current and write the upsert into the dimension table.

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.

EasyTechnical
77 practiced

Your orders table can contain multiple rows per customer because of updates and replays. A downstream report needs exactly one row per customer: the most recent order, and if two rows share the same timestamp the choice must be deterministic. How would you write the SQL, and how would you adjust it if the business later asks to keep every row tied for the latest timestamp?

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.