liveBook · Manning

Common table expression

As explained in DuckDB in Action

A common table expression is a named temporary query result defined within a SQL statement.

A common table expression (CTE) names a temporary query result inside a SQL statement. It separates a repeated or intermediate computation from the outer query, making analytical SQL easier to read and verify. section 1.7.3 section 10.1.5

Use a CTE when you want to:

  • Name a calculated relation and query it from an outer SELECT. section 10.1.5
  • Build an analytical statement incrementally and inspect intermediate results for correctness. section 1.7.3
  • Keep multi-step analysis concise instead of moving every computation into imperative code. section 4.0

Calculate and render reputation rates

WITH top_users AS ( SELECT DisplayName, Reputation, round(reputation / day(today() - CreationDate)) AS rate, day(today() - CreationDate) AS days, CreationDate FROM users WHERE Reputation > 1_000_000 ) SELECT DisplayName, Reputation, rate, bar(rate, 150, 300, 35) AS bar FROM top_users ORDER BY rate DESC; The CTE prepares filtered users and their reputation rates; the outer query adds a bar representation and orders the final result.

Figure 1.3 Using DuckDB in a data pipeline
figure

Use the pipeline diagram to place CTE-based SQL between data preparation and result consumption. section 1.6

How DuckDB in Action covers it

How deep it goes
Explains naming a query result with WITH and reusing it in an outer query, but does not discuss execution internals.
Examples
Demonstrates a filtered Stack Overflow user calculation that feeds a reputation-rate bar chart.
What it assumes
Assumes SQL tables, data ingestion, and data types while building from SELECT-based querying and analytical statements.
What you can do after
Apply it via SQL to decompose analytical queries, check intermediate logic, and format final results.
How it connects
Connects CTEs with SQL, views, subqueries, aggregations, window functions, and DuckDB.

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 DuckDB in Action. The section links point to the parts of the book it draws on.