Common table expression
Also called: CTE, WITH clause
A named query step written with WITH, used by the rest of the statement like a table.
Definition
CTEs let a long query read top to bottom as a list of steps. They exist only for one statement. WITH RECURSIVE repeats a step until it finds no new rows, which walks trees and graphs. PostgreSQL 12+ inlines a CTE used once and computes one used several times only once; data-modifying CTEs can DELETE … RETURNING rows and insert them elsewhere in the same statement.
In practice
WITH spending AS (SELECT customer_id, sum(total) AS spent FROM orders GROUP BY customer_id) SELECT * FROM spending WHERE spent > 500
Learn it in context
Lessons that use this term.