Interview Q&A · SQL · 10 questions in this topic
CTEs & Views — SQL Interview Q&A
Readable query architecture — WITH queries, recursive traversal, and views as stable interfaces. Part of Subqueries, CTEs & Views · 192 questions in the SQL bank.
What is a CTE (WITH clause) and why use one?
Answer
A CTE (WITH name AS (SELECT...)) names a query step reused in the main statement — readability (named steps beat nesting), multi-reference without repetition, and recursive power. Non-recursive CTEs are clarity tools; the planner may inline or materialize them.
One CTE per idea; chain them for pipelines instead of nesting subqueries four deep.
Example
WITH eng AS ( SELECT * FROM employees WHERE department = 'Engineering' ) SELECT AVG(salary) FROM eng;
💡 Named-steps-not-nesting is the CTE pitch.
Are CTEs an optimization fence (materialized)?
Answer
PostgreSQL <12 always materialized CTEs (optimization fence — predicates outside could not push in); 12+ inlines by default (MATERIALIZED forces the old behavior). Other engines vary. Consequence: pre-12 CTEs could hurt (no pushdown) or help (compute-once shared scans).
Know your version: fence semantics change plan shapes dramatically.
Example
-- PostgreSQL: WITH t AS MATERIALIZED (...) -- force compute-once -- WITH t AS NOT MATERIALIZED (...) -- force inline
💡 Version-dependent fencing is the deep-cut detail.
How do recursive CTEs work (org charts, trees, paths)?
Answer
UNION of anchor (base rows) and recursive member (joins CTE to itself, extending one level) until fixpoint — hierarchies, bills-of-materials, graph paths. Requires UNION (not UNION ALL semantics carelessly), termination thinking (cycle guards), and depth tracking for level/path columns.
Anchor plus self-extending step plus termination — the three-part anatomy.
Example
WITH RECURSIVE reports AS ( SELECT id, manager_id, name, 1 AS depth FROM employees WHERE manager_id IS NULL -- anchor UNION ALL SELECT e.id, e.manager_id, e.name, r.depth + 1 FROM employees e JOIN reports r ON e.manager_id = r.id ) SELECT * FROM reports;
What is a view and what is it good for?
Answer
A view is a stored named query acting as a virtual table — encapsulating complexity, stabilizing interfaces (rename-proofing), and enforcing row/column security boundaries. Ordinary views run their query fresh per use; materialized views store results for speed with refresh discipline.
Views are API contracts over evolving schemas.
Example
CREATE VIEW eng_roster AS SELECT id, name, salary FROM employees WHERE department = 'Engineering';
💡 Stored-query-as-interface is the view definition; materialized is the performance sibling.
Can you update through a view (updatable views, INSTEAD OF triggers)?
Answer
Simple single-table views (no aggregates/DISTINCT/GROUP BY) are updatable — writes pass through to the base table, optionally guarded by WITH CHECK OPTION (rejects rows that would vanish from the view). Complex views need INSTEAD OF triggers mapping writes explicitly.
WITH CHECK OPTION closes the write-then-disappear loophole.
Example
CREATE VIEW eng AS SELECT * FROM employees WHERE department = 'Engineering' WITH CHECK OPTION; -- inserts must satisfy the predicate
What is a materialized view and when is it worth it?
Answer
A materialized view stores query results physically — reads are table-fast, freshness costs refreshes (on-demand, scheduled, or incremental where supported). Worth it for expensive aggregations over slow-changing data (dashboards, rollups); wrong for fresh-data requirements.
Stale-read tolerance decides: dashboards yes, balances no.
Example
-- PostgreSQL: CREATE MATERIALIZED VIEW dept_stats AS SELECT department, COUNT(*), AVG(salary) FROM employees GROUP BY department; REFRESH MATERIALIZED VIEW dept_stats;
💡 Precompute-vs-freshness is the trade-off sentence.
How do you break a monster query into CTE stages?
Answer
One CTE per transformation (filtered base, enriched join, aggregated rollup, ranked final) with intention-revealing names, composed top-down. Each stage is independently testable (SELECT * FROM stage) — debugging becomes bisecting stages.
Staged CTEs are pipelines; nested subqueries are mazes.
Example
WITH base AS (...), enriched AS (SELECT ... FROM base JOIN ...), ranked AS (SELECT ..., ROW_NUMBER() OVER (...) FROM enriched) SELECT * FROM ranked WHERE rn <= 10;
💡 Testable-stages is the debugging payoff to emphasize.
How do you traverse graphs in SQL (paths, cycles, depth)?
Answer
Recursive CTE carrying a path array and depth: anchor at start nodes, extend along edges, stop on visited (cycle guard) or depth cap. Arrays (PostgreSQL) track visitation elegantly; strings concatenate portable paths.
SQL handles shallow hierarchies well; deep graph analytics belongs in graph engines — know the boundary.
Example
-- path-carrying recursion (PostgreSQL array ops): -- ... SELECT ..., path || e.id, depth + 1 ... WHERE NOT (e.id = ANY (path))
What are window functions doing inside CTE pipelines?
Answer
Ranking/filtering stages (ROW_NUMBER for dedup/top-N), running computations, and prior-row references — computed in a CTE, filtered outside (windows cannot appear in WHERE). CTE-plus-window layering keeps each concern separate and testable.
Compute in CTE, filter outside is the layering rule.
Example
WITH ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) SELECT * FROM ranked WHERE rn = 1; -- top earner per dept
CTE vs subquery vs temp table — how do you choose?
Answer
CTE: readable named steps, multi-reference, recursive — one statement scope. Subquery: single-use inline steps, terser for trivial cases. Temp table: multi-statement reuse, indexed, session-scoped — heavy pipelines and huge intermediates.
Readability ladder: subquery (trivial) → CTE (structured) → temp table (heavy/reused).
Key points
- 1CTE — named, reusable-in-statement, recursive.
- 2Subquery — inline, single-use.
- 3Temp table — indexed, cross-statement, session scope.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission