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
27 practiced
Compare and contrast how Common Table Expressions behave in PostgreSQL, SQL Server, BigQuery, and Snowflake. Focus on inlining vs materialization, support for recursive CTEs, optimization fences, and any vendor-specific syntax or hints that affect performance or correctness.
MediumTechnical
34 practiced
You have a multi-CTE ETL query: raw_events -> cleaned -> enriched -> deduplicated -> final_agg. Describe how you would test and validate each CTE step locally and in CI to ensure correctness and prevent regressions, including sampling strategies, checksums, row-count validation, and schema checks.
EasyTechnical
34 practiced
Describe the difference between correlated and non-correlated subqueries. Provide concise SQL examples showing (1) a non-correlated subquery used in WHERE, and (2) a correlated subquery evaluated per outer row. Explain when each type is evaluated during query execution and the performance implications.
MediumTechnical
29 practiced
Write this query: for each user, select their most recent order amount using a correlated scalar subquery: SELECT u.id, (SELECT amount FROM orders o WHERE o.user_id = u.id ORDER BY created_at DESC LIMIT 1) AS last_amount FROM users u. Then rewrite it using a CTE and window functions to improve performance for large datasets.
HardSystem Design
34 practiced
Design an approach to compute reachability (transitive closure) using recursive CTEs for a directed graph stored in edges(src, dst) with hundreds of millions of edges. Discuss feasibility, memory and time trade-offs, alternative strategies (graph DBs, iterative batch processing, Spark GraphX), and how to produce incremental updates when edges change.

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.