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
34 practiced
Refactor the following nested correlated subqueries into a CTE + JOIN + window-function approach for efficiency. Original (conceptual):
SELECT t.id, (SELECT COUNT(*) FROM events e WHERE e.tid = t.id AND e.value > (SELECT AVG(value) FROM events WHERE tid = t.id))
FROM targets t;
Explain your steps and provide the optimized SQL.
EasyTechnical
38 practiced
Explain the differences between: (a) an inline subquery / derived table, (b) a CTE (WITH clause), and (c) a temporary table. Cover scope, reuse, lifecycle, and typical scenarios where a data analyst would prefer one over the others.
MediumTechnical
34 practiced
Given a table of product reviews with columns (product_id, rating, review_date), write a SQL query that computes the weighted average rating per product where more recent reviews have higher weight. Use a CTE to compute weights and handle NULL ratings safely.
HardTechnical
27 practiced
Implement sessionization using SQL and CTEs: assign session_id per user where sessions are defined as sequences of events separated by less than 30 minutes. Table:
-- events(user_id int, occurred_at timestamp)
Return: user_id, session_start, session_end, event_count for each session. Explain window-function steps and edge cases.
EasyTechnical
35 practiced
Given the following tables:
-- customers(customer_id int, name text)
-- orders(order_id int, customer_id int, total_amount numeric, order_date date)
Write a SQL query (PostgreSQL) using a CTE to return customers whose average order value is greater than the overall average order value across all customers. Show the WITH clause and the final SELECT.

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.