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
34 practiced
Discuss how CTEs can impact query performance. Include examples of situations where CTEs may cause repeated work or materialization, and describe simple methods (EXPLAIN, ANALYZE, temporary tables, materialized views) to measure and mitigate performance issues when preparing features for ML pipelines.
MediumTechnical
34 practiced
Write a SQL example that demonstrates a performance regression caused by accidentally referencing a CTE multiple times in different branches of a UNION, and then provide a corrected version that computes the CTE once and reuses the result. Explain why the corrected version is better.
MediumTechnical
37 practiced
Some DBs (e.g., older Redshift versions) materialize CTEs and create temporary results for each CTE. Describe how you would test whether your database materializes CTEs, and write a minimal SQL experiment (two-part query) to demonstrate whether a CTE is re-evaluated each time it is referenced.
MediumTechnical
39 practiced
Some analytic queries use subqueries in GROUP BY or HAVING clauses. Show an example where a subquery in HAVING can be replaced with a CTE-driven aggregation to improve clarity and possibly performance. Use `orders(order_id, user_id, amount)` and compute users whose total spend exceeds the average user spend.
HardTechnical
39 practiced
How do partitioning strategies (table partitioning) interact with CTEs and subqueries? Describe how partition pruning can be preserved across CTE boundaries (if at all) and what you should be careful about when writing CTEs that filter on partition keys.

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.