liveBook · Manning

Common table expression

As explained in PostgreSQL Mistakes and How to Avoid Them

A common table expression is a named temporary query result defined with SQL WITH syntax and available within a larger statement.

A common table expression (CTE) is a named query fragment defined with WITH syntax and consumed by a larger SQL statement. It breaks complicated joins, filters, and subqueries into readable pieces, and the same result can be referenced more than once. section 2.3

A practical use is finding customers who received invoice reminders for unpaid service orders. Separate CTEs can isolate unpaid invoices and orders whose item is NULL, then the main query joins those results to contact and email tables. section 2.3

Readable invoice-reminder query

WITH unp AS (... unpaid invoices ...), ni AS (... service orders ...) SELECT DISTINCT email FROM customer_contact_details ccd JOIN unp ON unp.c = ccd.id JOIN ni ON ni.id = unp.og JOIN sent_emails se ON se.invoice = unp.id AND se.email_type = 'Invoice reminder'; Compared with nested subqueries, this structure makes each intermediate result explicit. EXPLAIN ANALYZE produced a simpler plan with faster planning and execution for this example. section 2.3

Treat readability as the primary benefit rather than assuming every CTE is faster. PostgreSQL’s optimizer may merge and reorder query parts, so inspect the resulting plan when performance matters. section 2.11 section 2.3

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Explains CTE structure through a complete rewrite and EXPLAIN ANALYZE comparison, but stops short of exhaustive optimizer internals.
Examples
Demonstrates unpaid invoices, service orders, reminder emails, nested subqueries, and contrasting query plans.
What it assumes
Assumes familiarity with joins, filters, subqueries, NULL values, and basic query-plan inspection.
What you can do after
Apply CTEs to restructure complex PostgreSQL queries and diagnose their planning and execution with EXPLAIN ANALYZE.
How it connects
Connects CTEs with subqueries, joins, query planners, selectivity, and EXPLAIN ANALYZE.

Also explained in

Compare how 6 books explain common table expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.