Question presented to candidate:
"What is a CTE, the WITH clause? Show me one, tell me when you would use it instead of a subquery, and tell me whether it changes performance."
What a strong answer should cover:
- A CTE is a named, temporary result set defined with
WITH name AS (...)and visible only to the one statement that follows it - Why use it: readability (a query read top to bottom as named steps), referencing the same intermediate result more than once, and chaining steps where each CTE can use the earlier ones
WITH RECURSIVElets a CTE refer to itself, for hierarchies and generated series (calendars, numbers)- Performance is engine-specific: since PostgreSQL 12 a non-recursive CTE referenced once is inlined like a subquery;
MATERIALIZED/NOT MATERIALIZEDoverride that, and SQLite has the same hints since 3.35.0 - Differences from a view (stored in the schema, reusable across queries) and a temporary table (persists for the session, can be indexed); PostgreSQL also allows data-modifying CTEs (
DELETE ... RETURNINGinsideWITH)
Code / implementation expected: Yes β a CTE that is referenced twice or chained, and ideally a short recursive one.
Schema used by the examples: