Break down queries with CTEs

PostgreSQL 19.0

A common table expression names a query result within one statement. Use it to separate steps that are easier to understand on their own.

On this page

Summarize before joining

First count the enrollments by course. Then join the named result to courses. This example uses the tables from Setup.

WITH totals AS (
  SELECT course_id, COUNT(*) AS student_count
  FROM enrollments
  GROUP BY course_id
)
SELECT c.title, COALESCE(t.student_count, 0) AS student_count
FROM courses AS c
LEFT JOIN totals AS t ON t.course_id = c.id
ORDER BY student_count DESC, c.id;

Look at the actual query plan

A CTE can improve readability. PostgreSQL may fold a nonrecursive, side-effect-free CTE into its parent query when it is referenced once. Use EXPLAIN to see whether restructuring changed the plan.

EXPLAIN
WITH course_roster AS (
  SELECT course_id, student_id FROM enrollments
)
SELECT student_id
FROM course_roster
WHERE course_id = 1;

Official references