# Common Table Expressions (WITH)

> Name each step of a long query with WITH, read it from top to bottom, and reuse a step more than once.

Subject: SQL | Lesson 25 of 44 | 5 min read
Interactive lesson: https://codewithanimation.in/sql/common-table-expressions
Previous: [EXISTS & Correlated Subqueries](https://codewithanimation.in/sql/exists-and-correlated-subqueries.md) | Next: [Recursive CTEs](https://codewithanimation.in/sql/recursive-ctes.md)

## Name a step, then use it

A **common table expression** (CTE) gives a name to a subquery. You write it with `WITH name AS (query)` before the main query, then use the name as if it were a table.

The manual describes a CTE as a temporary table that exists for just one query. You can write several, separated by commas, and a later one may use an earlier one.

## Readable queries

Nested subqueries must be read from the inside out. A chain of CTEs reads from top to bottom, like steps in a recipe, and each step can be tested on its own.

## Two steps, then the answer

```sql
WITH team_stats AS (
  SELECT team, count(*) AS n, round(avg(points), 1) AS avg_points
  FROM players
  GROUP BY team
), busy AS (
  SELECT team, n FROM team_stats WHERE n >= 3
)
SELECT team FROM busy ORDER BY team;
```

`team_stats` has one row per team: Red 3, Blue 3, Green 2. `busy` reads it by name and keeps the teams with at least 3 players: Red and Blue. The final `SELECT` reads `busy`.

A name can be used more than once in the main query, for example to compare each team with the average of all teams. You do not have to repeat the subquery text.

## Common mistake: A CTE is not a saved table

A CTE exists only inside its one statement. The next statement cannot use it. If you need a reusable name, you want a view, which a later lesson covers.

PostgreSQL may merge a CTE that is used once into the main query, and by default it computes a CTE that is used more than once only one time. You can force the choice with `MATERIALIZED` or `NOT MATERIALIZED`. For learning, the result is the same either way.

A CTE cannot be referred to before it is defined. Write the steps in the order they are needed.

## Tip: One idea per CTE

Give each CTE one clear job and a name that says what it holds, such as `busy_teams`. If a step is hard to name, it is probably doing two things.

## Try it: Walk through the steps

Press each step to see the table it produces, change the threshold, and switch on Without WITH to compare the nested version.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/common-table-expressions

## Check yourself

### Question 1

How long does a CTE named `busy` exist?

- A. Only while the one statement that defines it runs
- B. Until the end of the session
- C. Forever, like a table

Correct answer: A

A CTE is a temporary name that exists just for one query.

- Why not B: A CTE is not stored anywhere. It exists only for its own statement.
- Why not C: A CTE is not a table in the database. A view or a real table would be.

### Question 2

In `WITH a AS (...), b AS (SELECT * FROM a WHERE ...) SELECT * FROM b`, can `b` use `a`?

- A. Yes, a later CTE can use an earlier one
- B. No, each CTE is separate
- C. Only if a is declared MATERIALIZED

Correct answer: A

A CTE can refer to the CTEs defined before it in the same WITH list.

- Why not B: CTEs can build on each other. That is one of their main uses.
- Why not C: MATERIALIZED only affects how the database computes it, not whether you can use the name.

### Question 3

What is the main benefit of a CTE compared with a nested subquery?

- A. The query reads from top to bottom and each step has a name
- B. It always runs faster
- C. It saves the data for later queries

Correct answer: A

CTEs mainly make long queries easier to read, write and test.

- Why not B: Speed is usually the same. The benefit is readability.
- Why not C: A CTE is gone when the statement ends.

## Remember this

- WITH name AS (query) gives a subquery a name for the rest of one statement.
- Several CTEs are separated by commas, and a later one can use an earlier one.
- A CTE exists only for its own statement. It is not saved.
- A CTE is for readability. The result is the same as the nested version.
