What is 'CTE' (Common Table Expression) and its use cases?
Instruction: Define 'CTE' and provide examples of scenarios where it's particularly useful.
Updated
Official answer
A common table expression names an auxiliary query within a statement using WITH. It can make successive transformations easier to read without creating a permanent table.
This PostgreSQL example returns one row, total = 5:
WITH quantities(qty) AS (VALUES (2), (3))
SELECT SUM(qty) AS total FROM quantities;
The name quantities belongs to this statement; a later independent query cannot reuse it. CTE syntax does not guarantee materialization, caching or better performance. PostgreSQL can fold eligible CTEs into the surrounding query; use the actual plan to understand execution.
Recursive CTEs can traverse hierarchies or generate a sequence. They need a terminating condition and, for graphs, a way to address cycles. Their availability and syntax depend on the engine.
Statement scope is not a promise of no side effects. PostgreSQL also supports data-modifying statements in WITH; those can change persistent data. Even a read-only CTE can consume substantial resources or wait for locks.
Assessment: Explain scope, identify a useful decomposition, and separate readability from execution guarantees.