# CTE vs subquery in SQL

Source: https://sqlstreak.com/sql/cte-vs-subquery · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** A CTE (`WITH name AS (…)`) and a subquery in `FROM` can express the same query and return the same rows. The CTE names the step and puts it first, so the query reads top to bottom, and you can use it more than once or make it recursive.

## Side by side

| | CTE (WITH) | Subquery |
| --- | --- | --- |
| Where it's written | Before the main query, with a name | Inside the query that uses it |
| Use it twice | Yes, by name | Repeat the subquery |
| Recursion | WITH RECURSIVE | Not possible |
| Reads best for | Several steps in a row | One short inner step |

## Examples

### As a CTE

Orders with more than four items: first total the items per order, then filter.

```sql
WITH order_sizes AS (
  SELECT order_id, SUM(quantity) AS items
  FROM order_items
  GROUP BY order_id
)
SELECT order_id, items
FROM order_sizes
WHERE items > 4
ORDER BY order_id;
```

Result (both engines):

| order_id | items |
| --- | --- |
| 6 | 6 |
| 10 | 5 |
| 13 | 5 |

### As a subquery

The same question with the step written inside FROM. Same rows.

```sql
SELECT order_id, items
FROM (SELECT order_id, SUM(quantity) AS items
      FROM order_items
      GROUP BY order_id) order_sizes
WHERE items > 4
ORDER BY order_id;
```

Result (both engines):

| order_id | items |
| --- | --- |
| 6 | 6 |
| 10 | 5 |
| 13 | 5 |

### A CTE used twice

The biggest orders: the CTE is read once in FROM and once in the subquery that finds the maximum.

```sql
WITH order_sizes AS (
  SELECT order_id, SUM(quantity) AS items
  FROM order_items
  GROUP BY order_id
)
SELECT order_id, items
FROM order_sizes
WHERE items = (SELECT MAX(items) FROM order_sizes);
```

Result (both engines):

| order_id | items |
| --- | --- |
| 6 | 6 |

### Asking for the step to run once: MATERIALIZED

Both databases accept a hint that makes the CTE run once on its own instead of being merged into the main query.

```sql
WITH order_sizes AS MATERIALIZED (
  SELECT order_id, SUM(quantity) AS items
  FROM order_items
  GROUP BY order_id
)
SELECT COUNT(*) AS big_orders
FROM order_sizes
WHERE items > 4;
```

Result (both engines):

| big_orders |
| --- |
| 3 |

## When to use which

- **CTE (WITH):** Queries with several steps, a step you need twice, or recursion (sequences, calendars, org charts).
- **Subquery:** A short, one-off inner query, especially a single value in WHERE (`WHERE price > (SELECT AVG(price) …)`).

## Common mistakes

- Expecting a CTE to be faster by itself: a CTE used once is usually planned just like the subquery. Measure with EXPLAIN.
- Forgetting the comma between two CTEs: `WITH a AS (…), b AS (…)`.
- Ending the CTE with a semicolon before the main query: the WITH and the SELECT are one statement.
