Concept · Advanced SQL

WITH and CTE

WITH defines a CTE: a named helper result that exists only while the statement using it runs.

WITH and CTE example

First we isolate the shipped orders. Then we calculate the shipped amount per customer:

SQL
WITH shipped_orders AS (
  SELECT customer_id, total
  FROM orders
  WHERE status = 'shipped'
)
SELECT customer_id,
       ROUND(SUM(total), 2) AS total_shipped
FROM shipped_orders
GROUP BY customer_id
ORDER BY customer_id;

Check the result with small data

First we calculate sales per team, then we filter those sums.

Self-contained query · SQLite
WITH sales(team, amount) AS (
  VALUES ('A',10),('A',15),('B',7)
), totals AS (
  SELECT team, SUM(amount) AS total
  FROM sales GROUP BY team
)
SELECT team, total FROM totals WHERE total > 10;
Query result
teamtotal
A25

The totals CTE has a name you can use in the statement that immediately follows. It does not create a permanent table you can query later.

Check your understanding: Which team was dropped for having a low total?

Show answer

Team B, which adds up to 7 and does not exceed 10.

Common mix-ups with WITH and CTE

Trying to use the CTE in a later statement

Problem query
WITH shipped AS (
  SELECT * FROM orders WHERE status = 'shipped'
);

SELECT * FROM shipped;

The definition WITH must be attached to the statement that uses the CTE. The semicolon ends the statement before the SELECT. To reuse a result in later queries, look at a view or a temporary table.

Key differences between engines

Ordinary CTEs are available in current versions of PostgreSQL, SQLite, MySQL and SQL Server, although older versions may not support them. Recursive CTEs add rules of their own and are best studied separately. PostgreSQL, SQLite and MySQL let the optimiser decide whether to inline or materialise certain results; that is why WITH improves clarity first, not necessarily speed. In SQL Server, the statement before WITH must be terminated properly, and people often write ;WITH when there is a risk of leaving out that separator.

A CTE names a step, but does not save its result

A WITH defines one or more named queries that the main statement can use as if they were tables. It lets you split a long query into readable steps: first you summarise per customer, then you filter that summary.

The CTE exists only during the statement that declares it. It does not create a table or keep data between runs; for that you need a view, a temporary table or a real table. Depending on the engine and version, the CTE may be evaluated once or expanded every time it is referenced, so do not assume it improves performance.

Check each step separately: run the CTE's query on its own and confirm it returns the granularity you expect before using it. Avoid generic names such as data and name the calculated column so the final query can be read without looking back at the previous step.

Self-contained case to check in SQLite

The first step adds up the orders per customer; the final query filters those sums.

Data and query · SQLite
WITH orders(customer, total) AS (
  VALUES ('Amy', 30), ('Amy', 20), ('Liam', 15)
), by_customer AS (
  SELECT customer, SUM(total) AS amount
  FROM orders
  GROUP BY customer
)
SELECT customer, amount
FROM by_customer
WHERE amount > 20
ORDER BY customer;
Verified result of the self-contained case
customeramount
Amy50

The by_customer CTE produces one row per customer; those sums are then filtered. Liam adds up to 15 and is left out.

Check your interpretation: Why can't by_customer be used in a later statement?

Show answer

Because a CTE only exists within the statement that starts with WITH. When that statement ends, it disappears; to reuse it you would have to declare it again or create a view.

Technical questions: PostgreSQL: SELECT, columns and aliases (opens in a new tab).