InterviewStack.io LogoInterviewStack.io

CTEs & Subqueries Questions

Common Table Expressions (CTEs) and subqueries in SQL, including syntax, recursive CTEs, usage patterns, performance implications, and techniques for writing clear, efficient queries. Covers when to use CTEs versus subqueries, refactoring patterns, and potential pitfalls.

MediumTechnical
31 practiced
Using CTEs, compute the earliest date when cumulative sales reach 80% of the total sales. Schema: sales(sale_date DATE, amount DECIMAL). Return the threshold_date and cumulative_percentage at that date. Explain tie-breaking if multiple dates have the same cumulative percentage.
EasyTechnical
30 practiced
You are asked to explain to a stakeholder when to use a CTE in dashboard queries versus an inline subquery for readability and maintenance. Describe the trade-offs (readability vs performance), and what database-specific considerations you would mention.
HardTechnical
32 practiced
Discuss how CTE usage can interact with query planner statistics and cardinality estimation. Provide an example where misestimated cardinality inside a CTE leads to a bad join order, and explain steps to improve planning (ANALYZE, extended statistics, histograms, rewriting queries).
EasyTechnical
35 practiced
Using a CTE, compute a 7-day rolling average of daily active users (DAU) from an events table with schema:
sql
events(user_id INT, event_date DATE)
Instructions: first aggregate unique users per date in a CTE, then compute the 7-day rolling average. Explain how you handle missing dates in the range.
MediumTechnical
30 practiced
Discuss the pitfalls of using SELECT * inside CTEs of long-lived reporting queries. Cover risks like schema drift, accidental inclusion of large columns, and maintainability. Provide concrete recommendations to mitigate these risks.

Unlock Full Question Bank

Get access to hundreds of CTEs & Subqueries interview questions and detailed answers.

Sign in to Continue

Join thousands of developers preparing for their dream job.