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
38 practiced
Explain whether CTEs are always materialized by the database engine and how materialization versus inlining affects performance. Discuss differences you are aware of across engines (Postgres behavior across versions, SQL Server, BigQuery, Snowflake) and how that knowledge should influence whether you choose a CTE, a subquery, or a temporary table in production.
EasyTechnical
27 practiced
Write a SQL query (PostgreSQL) that uses a CTE to compute the average order amount per user and returns only users with average > 100. Table schema: orders(order_id INT, user_id INT, amount NUMERIC, created_at TIMESTAMP). Example input: user 1 amounts [150, 200], user 2 amounts [20, 30]. Expected output: user_id 1, avg_amt 175.0. Use a WITH clause and return columns (user_id, avg_amt).
MediumTechnical
37 practiced
For schema products(product_id, category_id, price) and categories(category_id, name), write a query that returns the top 3 most expensive products per category using LATERAL in Postgres, then rewrite it using a CTE or window function. Explain which version is more efficient and in what cases LATERAL is preferable or unsupported (e.g., MySQL pre-8, Snowflake variations).
EasyTechnical
33 practiced
Given table events(event_id BIGINT PRIMARY KEY, user_id INT, event_type TEXT, ts TIMESTAMP), write a SQL query using a CTE and window functions to deduplicate events per (user_id, event_type) keeping the earliest ts per group and returning the deduplicated rows (event_id, user_id, event_type, ts). Use standard SQL/Postgres syntax and explain how your query handles ties and NULL timestamps.
HardTechnical
38 practiced
In Spark SQL you see a multi-stage iterative algorithm implemented with chained CTEs that leads to multiple Spark jobs and recomputation. Explain how Spark's Catalyst optimizer handles CTEs, why repeated references might trigger recomputation, and show how you would rework the code using DataFrame.persist(), checkpoint(), or caching to avoid repeated work. Provide short PySpark snippets illustrating the fix.

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.