Interview Q&A · SQL · 10 questions in this topic

CTEs & Views — SQL Interview Q&A

All SQL topics

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

Example.sqlsql
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

Example.sqlsql
-- 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

Example.sqlsql
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;

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits