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
33 practiced
You're asked to pre-aggregate product sales for a BI dashboard to reduce query time on a 100M-row fact table. Describe using CTEs as part of a pipeline to create incremental, partitioned pre-aggregations and show a sample SQL pattern for the incremental step using `WITH` to stage new rows before merging into the aggregate table.
MediumTechnical
32 practiced
Show a SQL pattern using CTEs that handles late-arriving events in an ETL merge process. Assume `staging_events` contains new and updated rows and `events` is the target table. Provide pseudocode for staging, deduping, and MERGE/UPSERT (Snowflake or Postgres) using a `WITH` clause.
MediumTechnical
29 practiced
Discuss the benefits and pitfalls of using CTEs for readability and maintainability in BI SQL code. Provide two real-world examples: one where CTEs make a long metric pipeline clear, and one where CTEs hide expensive operations and caused production issues.
MediumTechnical
35 practiced
Write SQL using CTEs to compute weekly retention for user cohorts defined by signup week. For each cohort, show the number of users active in week 0 through week 12. Use window functions where helpful and explain how you would visualize this in a dashboard.
HardTechnical
29 practiced
Here is an example EXPLAIN ANALYZE snippet for a Postgres query that uses a CTE:
Seq Scan on orders (cost=0.00..10000.00 rows=1000000 width=40) CTE Scan on cte_customers (cost=100.00..500.00 rows=10000 width=50)
Given this simplified output, identify likely bottlenecks and propose three concrete optimizations (indexes, rewrite CTE, partitioning) to reduce runtime for a BI report that times out.

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.