Common Table Expressions with WITH
Lesson 14 of 33 in the SQL / MySQL learning path.
How do I name a subquery so a report is readable?
A report that nests every aggregate in one SELECT is hard to read out loud. A common table expression gives that inner result a name for the rest of one statement. WITH course_counts AS computes the student count and the average grade points per course. The outer SELECT joins that name to courses and keeps the groups with at least two students. Nothing is stored. The name disappears when the statement ends.
This is a non-recursive CTE, which is the form you want for a roster summary. MySQL 8 supports it. Recursive CTEs, written WITH RECURSIVE, can walk a tree such as a mentor chain, and they need a stopping condition. This lesson does not build that walk. It uses the same school numbers as the aggregate lesson so you can see the readable form of a report you already know.
Syntax & Parameters
WITH cte_name AS (
SELECT column_list
FROM table_name
GROUP BY column_list
)
SELECT column_list
FROM cte_name
WHERE metric >= 2;
Example
CREATE DATABASE IF NOT EXISTS school CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE school;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS courses;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(120) NOT NULL,
email VARCHAR(254) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE courses (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
code VARCHAR(16) NOT NULL,
title VARCHAR(160) NOT NULL,
seats SMALLINT UNSIGNED NOT NULL DEFAULT 30,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_courses_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE enrollments (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
course_id INT UNSIGNED NOT NULL,
grade_points DECIMAL(4,2) NULL,
enrolled_on DATE NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_enrollments_user_course (user_id, course_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO users (name, email, password_hash, created_at) VALUES
('Ada Lovelace', 'ada@school.test', 'sample-hash-not-a-secret', '2026-01-15 09:00:00'),
('Grace Hopper', 'grace@school.test', 'sample-hash-not-a-secret', '2026-02-11 09:30:00'),
('Alan Turing', 'alan@school.test', 'sample-hash-not-a-secret', '2026-03-02 11:00:00');
INSERT INTO courses (code, title, seats, created_at) VALUES
('CS101', 'Intro to Databases', 30, '2026-01-10 08:00:00'),
('CS220', 'Relational Design', 24, '2026-01-10 08:05:00'),
('CS310', 'Query Tuning', 18, '2026-01-10 08:10:00');
INSERT INTO enrollments (user_id, course_id, grade_points, enrolled_on) VALUES
(1, 1, 3.70, '2026-01-20'),
(2, 1, 4.00, '2026-01-20'),
(3, 1, 3.30, '2026-01-20'),
(1, 2, 3.00, '2026-01-21'),
(2, 2, 3.50, '2026-01-21'),
(3, 3, 2.70, '2026-01-22');
WITH course_counts AS (
SELECT e.course_id, COUNT(*) AS student_count,
ROUND(AVG(e.grade_points), 2) AS avg_points
FROM enrollments AS e
GROUP BY e.course_id
)
SELECT c.code, c.title, cc.student_count, cc.avg_points
FROM course_counts AS cc
INNER JOIN courses AS c ON c.id = cc.course_id
WHERE cc.student_count >= 2
ORDER BY cc.student_count DESC, c.code;
Expected Output
code | title | student_count | avg_points CS101 | Intro to Databases | 3 | 3.67 CS220 | Relational Design | 2 | 3.25 2 rows in set CS310 is inside course_counts with student_count 1 and is removed by WHERE student_count >= 2.
Line-by-Line Walkthrough
- The script creates the school tables and loads the same six enrollments used to practice aggregates: three in CS101, two in CS220, and one in CS310.
- WITH course_counts AS starts the statement. The name course_counts exists only for this statement.
- Inside the CTE, GROUP BY course_id computes student_count and the rounded average grade points.
- CS101 averages 3.67, CS220 averages 3.25, and CS310 averages 2.70. All three groups exist inside the CTE.
- The outer SELECT joins course_counts to courses on the course id so the report can show the code and the title.
- WHERE cc.student_count >= 2 filters the named result. CS310 has one student and drops out. This WHERE is legal because student_count is a column of course_counts, not an aggregate of the outer query.
- ORDER BY student_count DESC, code matches the aggregate lesson: CS101, then CS220.
- You can reference course_counts more than once in this statement if a later report needs it. The next statement cannot see the name.
- The CTE is non-recursive. It does not refer to itself.
- WITH RECURSIVE is the separate form for a tree walk, such as following mentor_id from a student up to the head of a department, and that form needs an anchor member and a condition that stops.
Common Pitfalls & Security
A CTE reads like a temporary table and it is not one you can query a minute later. The name lives for the single statement that starts with WITH. MySQL 5.7 rejects WITH entirely. Recursive CTEs that lack a stop condition can run until the server hits its recursion limit, which is why this lesson stays non-recursive. Filter the named result in the outer query when the column already exists there.
- SELECT * FROM course_counts in a second statement fails because the CTE is gone. Repeat WITH, or create a real temporary table when the next statement must reuse the rows.
- MySQL 5.7 has no CTE support. This script targets MySQL 8.
- A recursive walk of mentor_id without a stopping predicate burns the cte_max_recursion_depth limit. Add a depth cap and a real end condition before you write WITH RECURSIVE.
- WHERE inside the CTE and WHERE outside it answer different questions. The CTE in this sample keeps every course, and the outer WHERE drops the small class.
- Naming a CTE the same as a real table hides that table for the statement. course_counts is not a base table. Keep the name obviously derived.
- An UPDATE or DELETE without WHERE is a catastrophe. A readable report is still a read. Do not edit grades from a CTE statement that forgot its row filter.
Best Practices & Modern Standards
Name the grouped part of a report when a reader would otherwise parse two nested selects. Keep the CTE to one job, join it to the lookup table for labels, and filter the named columns in the outer query. Stay non-recursive until the question is actually a tree.
Use WITH RECURSIVE only for a hierarchy you can bound, such as a short mentor chain, and test the stop condition on a tiny set of users first. Index the columns the CTE groups and joins, here course_id, so the readable form is also the fast form.
Real-World Use
The registrar publishes a one-page course report: code, title, how many students enrolled, and the average grade points, hiding any course with fewer than two students. Those facts live in enrollments and courses, and the students are the users behind the enrollment rows. WITH course_counts names the math so the outer query reads like the report. Staff can check CS101 and CS220 without decoding a nested aggregate in the middle of the select list.
Frequently Asked Questions
Does WITH create a table I can query later?
No. course_counts exists only while this statement runs. The next statement must define the CTE again, or you can insert the result into a real table if a later step needs the rows.
How is this different from the GROUP BY lesson?
The numbers match that lesson: CS101 has 3 students and CS220 has 2. WITH names the grouping so the outer query can join the title and filter student_count as an ordinary column.
When would I use WITH RECURSIVE?
Use it to walk a hierarchy, such as a mentor chain stored with mentor_id. It needs an anchor row and a condition that stops. A course-count report does not need recursion, so this sample stays with a plain WITH.
Which MySQL versions accept this statement?
MySQL 8.0 and newer. MySQL 5.7 reports a syntax error at WITH. The rest of this school schema can be discussed on older servers, and this statement cannot.