Common Table Expressions

Updated · 8 min read
mediumPostgreSQL 18sqlctewithsubqueriesreadabilityinterview

A common table expression (CTE) in SQL is a named, temporary result set that is defined with the WITH keyword and used by the query that follows it. It is used to break a long query into small, named steps that are read from top to bottom. A CTE exists only while its query runs; it is not stored like a table or a view. In this lesson, we will learn the syntax of a CTE, how to chain several CTEs, and how CTEs compare with subqueries and views.

In One Minute

  • A CTE is written as WITH name AS (SELECT ...) before the main query.
  • The main query uses the CTE's name like a table.
  • Several CTEs can be chained with commas; each one can use the ones before it.
  • A CTE lasts for one statement only.
  • CTEs make queries easier to read; they usually run as fast as the same subquery.

What Is a CTE?

A CTE is a subquery that is given a name and moved to the front of the statement. Instead of nesting one query inside another, we write each step once, name it, and then use the name. The main benefits are:

  • Readability: each step has a name that says what it holds, such as totals or owed.
  • Reuse within a query: a CTE can be referenced more than once in the main query.
  • Step-by-step logic: later CTEs build on earlier ones, like the lines of a recipe.

Syntax

SQL
WITH cte_name AS (
  SELECT ...
)
SELECT ...
FROM cte_name;

The WITH clause comes first. The parentheses hold the CTE's query. The main query follows, with no comma, and uses cte_name like a table.

Example: A Named Step

The following query names each student's total paid as totals, and then joins it to students:

SQL▶ Try it
WITH totals AS (
  SELECT student_id, sum(amount_usd) AS total
  FROM payments
  GROUP BY student_id
)
SELECT s.first_name, t.total
FROM totals AS t
JOIN students AS s USING (student_id)
ORDER BY t.total DESC;
Output
 first_name |  total
------------+---------
 Srihitha   | 1700.00
 Navika     |  450.00
(2 rows)

Explanation: The CTE totals returns one row per paying student. The main query treats totals as a table, joins it to students for the names, and sorts by the total. The same query written as a subquery would put the GROUP BY inside the FROM clause; with a CTE, the steps read in order.

The CTE totals summarizes payments; the main query joins it to students

Several CTEs in a Row

More than one CTE can be defined in a single WITH clause, separated by commas. Each CTE can use the CTEs defined before it.

SQL
WITH first_step AS (...),
     second_step AS (SELECT ... FROM first_step ...)
SELECT ... FROM second_step;

The following query finds students who paid more than the average paying student:

SQL▶ Try it
WITH totals AS (
  SELECT student_id, sum(amount_usd) AS total
  FROM payments
  GROUP BY student_id
),
average AS (
  SELECT avg(total) AS avg_total FROM totals
)
SELECT t.student_id, t.total, round(a.avg_total, 2) AS avg_total
FROM totals AS t
CROSS JOIN average AS a
WHERE t.total > a.avg_total;
Output
 student_id |  total  | avg_total
------------+---------+-----------
        101 | 1700.00 |   1075.00
(1 row)

Explanation: totals sums each student's payments. average uses totals to compute the average of those sums, $1,075.00. The main query compares each total with the average. Without CTEs, totals would have to be written twice.

A longer chain reads like a report. The following query works out what each enrollment still owes, in two named steps:

SQL▶ Try it
WITH paid AS (
  SELECT student_id, course_id, sum(amount_usd) AS paid
  FROM payments
  GROUP BY student_id, course_id
),
owed AS (
  SELECT e.student_id, c.title, c.fee_usd - coalesce(p.paid, 0) AS owed
  FROM enrollments AS e
  JOIN courses AS c USING (course_id)
  LEFT JOIN paid AS p USING (student_id, course_id)
)
SELECT *
FROM owed
WHERE owed > 0
ORDER BY student_id, title;
Output
 student_id |    title    |  owed
------------+-------------+--------
        101 | SQL Basics  | 200.00
        102 | Java Basics | 450.00
        102 | SQL Basics  | 400.00
(3 rows)

Explanation: paid totals the payments for each enrollment. owed joins every enrollment to its course fee and its payments, using a left join so that unpaid enrollments are kept. The main query keeps only the enrollments with something still owed.

paid feeds owed, and owed feeds the final SELECT

CTEs vs Subqueries vs Views

FeatureCTESubqueryView
Has a nameYesNo (only an alias in FROM)Yes
Lasts forOne statementOne statementUntil dropped
Can be used twice in a queryYesNo; it must be repeatedYes
Stored in the databaseNoNoYes, as a definition
Best forMulti-step queriesShort, one-off piecesLogic shared by many queries

Note that in PostgreSQL 12 and later, a CTE that is used once is usually inlined: the planner treats it like the same subquery, so there is no speed penalty. To force PostgreSQL to compute a CTE once and keep its result, write WITH name AS MATERIALIZED (...). CTEs are supported by PostgreSQL, MySQL 8.0 and later, SQL Server, Oracle and SQLite.

The same totals as a subquery, a CTE and a view: one statement, one statement, or saved

Common Mistakes

A comma before the main query. WITH a AS (...), SELECT ... is a syntax error. Commas go only between CTEs.

Using a CTE in a later statement. It no longer exists after its statement ends.

Referring to a CTE before it is defined. Each CTE can use only the ones written before it (except in recursive CTEs).

Assuming a CTE is always computed once. In PostgreSQL 12 and later, single-use CTEs are inlined; use MATERIALIZED when you need one computation.

Interview Corner

What is a CTE?

A common table expression is a named, temporary result set defined with WITH before a query. The query can use it like a table; it exists only for that statement.

What's the difference between a CTE and a subquery?

They can express the same logic. A CTE has a name, sits before the main query, and can be referenced more than once; a subquery is written inline where it's used.

What's the difference between a CTE and a view?

A CTE lasts for one statement and isn't stored; a view is saved in the database and can be used by any query until it's dropped.

Practice

Challenge: Using a CTE named monthly, compute the total paid in each month (use date_trunc('month', paid_on)::date), then show only the months with more than $300.00, sorted by month.

Show solution
SQL▶ Try it
WITH monthly AS (
  SELECT date_trunc('month', paid_on)::date AS month,
         sum(amount_usd) AS total
  FROM payments
  GROUP BY 1
)
SELECT month, total
FROM monthly
WHERE total > 300
ORDER BY month;
Output
   month    |  total
------------+---------
 2025-08-01 |  450.00
 2025-12-01 | 1025.00
(2 rows)

The CTE builds one row per month, and the main query filters those rows. The same result could be written with HAVING, but the CTE keeps the "build" and the "filter" in separate, named steps.

Quick check: Common table expressions

3 questions
1How long does a CTE exist?
2Which is correct syntax for two CTEs?
3Can the second CTE use the first?

Key Takeaways

You want toWrite
Name a stepWITH totals AS (SELECT ...) SELECT ... FROM totals
Chain stepsWITH a AS (...), b AS (SELECT ... FROM a) SELECT ... FROM b
Force one computationWITH totals AS MATERIALIZED (...)

Was this tutorial helpful?

Lesson 62 of 115