InterviewStack.io LogoInterviewStack.io

Common Table Expressions and Subqueries Questions

Covers writing and structuring complex SQL queries using Common Table Expressions and subqueries, including when to prefer one approach over another for readability, maintainability, and performance. Candidates should be able to author WITH clauses to break multi step logic into clear stages, implement recursive CTEs for hierarchical data, and use subqueries in SELECT, FROM, and WHERE clauses. This topic also includes understanding correlated versus non correlated subqueries, how subqueries interact with joins and window functions, and practical guidance on choosing CTEs, subqueries, or joins based on clarity and execution characteristics. Interviewers may probe syntax, typical pitfalls, refactoring nested queries into CTEs, testing and validating each step of a CTE pipeline, and trade offs that affect execution plans and index usage.

HardTechnical
28 practiced
Explain how writing predicates incorrectly inside CTEs can prevent partition pruning or index usage. Given a partitioned table by day, show an example predicate that disables pruning and rewrite it to enable pruning and use indexes effectively.
MediumTechnical
35 practiced
When would you use a recursive CTE for hierarchical queries versus using a graph database or denormalized closure table? Discuss considerations such as expected tree depth, update frequency, ad-hoc queries, and analytics performance.
HardTechnical
26 practiced
Subqueries that compute a date threshold like WHERE created_at >= (SELECT MAX(created_at) - INTERVAL '7 days' FROM table) can interfere with index range scans. Explain why and rewrite the pattern to compute the threshold separately so the predicate can use an index or partition pruning.
MediumTechnical
28 practiced
Refactor this correlated-subquery style snippet into an equivalent JOIN + GROUP BY to improve performance: SELECT u.user_id, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.user_id AND o.status = 'completed') AS completed_orders FROM users u; Provide the rewritten SQL and explain index choices that help the JOIN version.
MediumTechnical
32 practiced
From a data-scientist perspective, outline a rule-of-thumb guide for choosing between CTE, subquery, or join in analytics SQL. Cover readability, reusability, potential for materialization, and how to validate performance impact in an iterative model-building workflow.

Unlock Full Question Bank

Get access to hundreds of Common Table Expressions and Subqueries interview questions and detailed answers.

Sign in to Continue

Join thousands of developers preparing for their dream job.