Subqueries in WHERE and in the SELECT List
Lesson 13 of 33 in the SQL / MySQL learning path.
How do I filter rows using a nested SELECT?
Some questions compare a student with a number you have to compute first. The average course load is that number. A subquery is a SELECT nested inside another statement. In the select list it adds a column, here each student course count and the school average. In WHERE it keeps the students whose own count is greater than that average. The average is the mean of the per-student counts among people who have at least one enrollment, because the inner GROUP BY reads enrollments.
Ada has three courses, Grace two, and Alan one, so the average is 2. Ada is the only student above it. Katherine has an account and zero enrollments, so she sits outside that average. The nested selects stay readable, and the next lesson gives the average a name with a CTE.
Syntax & Parameters
SELECT column_list,
(SELECT COUNT(*) FROM enrollments WHERE enrollments.user_id = users.id) AS metric
FROM users
WHERE (SELECT COUNT(*) FROM enrollments WHERE enrollments.user_id = users.id) > (
SELECT AVG(course_count) FROM (
SELECT COUNT(*) AS course_count FROM enrollments GROUP BY user_id
) AS per_user
);
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,
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'),
('Katherine Johnson', 'katherine@school.test', 'sample-hash-not-a-secret', '2026-04-01 09:00:00');
INSERT INTO courses (code, title, seats) VALUES
('CS101', 'Intro to Databases', 30),
('CS220', 'Relational Design', 24),
('CS310', 'Query Tuning', 18);
INSERT INTO enrollments (user_id, course_id, enrolled_on) VALUES
(1, 1, '2026-01-20'),
(1, 2, '2026-01-21'),
(1, 3, '2026-01-22'),
(2, 1, '2026-01-20'),
(2, 2, '2026-01-21'),
(3, 1, '2026-01-20');
SELECT u.id, u.name,
(SELECT COUNT(*) FROM enrollments AS e WHERE e.user_id = u.id) AS course_count,
(SELECT ROUND(AVG(per_user.course_count), 2) FROM (
SELECT COUNT(*) AS course_count FROM enrollments GROUP BY user_id
) AS per_user) AS avg_course_count
FROM users AS u
WHERE (SELECT COUNT(*) FROM enrollments AS e WHERE e.user_id = u.id) > (
SELECT AVG(per_user.course_count) FROM (
SELECT COUNT(*) AS course_count FROM enrollments GROUP BY user_id
) AS per_user
)
ORDER BY course_count DESC, u.id;
Expected Output
id | name | course_count | avg_course_count 1 | Ada Lovelace | 3 | 2.00 1 row in set Average course count among students who have at least one enrollment: (3 + 2 + 1) / 3 = 2.
Line-by-Line Walkthrough
- The script creates users, courses, and enrollments and loads four students. Katherine has no enrollment rows.
- Ada is enrolled in CS101, CS220, and CS310. Grace is in two courses. Alan is in one. The counts are 3, 2, and 1.
- The select-list subquery counts enrollments for the current user. It is correlated: e.user_id = u.id refers to the outer row.
- The second select-list subquery is not correlated. It averages the per-student counts from a derived table and rounds to two decimals, which is 2.00 here.
- The derived table groups enrollments by user_id. Students with zero courses, including Katherine, are absent from that average.
- MySQL requires the alias per_user on the derived table. The outer query reads per_user.course_count.
- The WHERE subquery repeats the correlated count and keeps the user only when that count is greater than the average.
- A scalar subquery used with > must return one column and one row. AVG does that. A subquery that returns many rows raises error 1242.
- Ada at 3 is the only student above 2. Grace equals the average and is excluded. Alan and Katherine are below it.
- The same result can be written as a join plus GROUP BY. The subquery form makes the comparison easy to point at. The next lesson names that inner summary with WITH so it is not repeated.
Common Pitfalls & Security
A subquery in WHERE that returns more than one row cannot be compared with a single greater-than sign. AVG returns one value, so this comparison is valid. An empty enrollments table makes AVG return null, and a comparison with null matches nobody. The correlated count runs once per outer row, which is clear on four students and worth rewriting as a join when the directory is large. The average in this lesson ignores students who have no courses.
- Error 1242 means the subquery returned more than one row. Aggregate it, or use IN when you truly want a list of values.
- If enrollments is empty, AVG returns NULL and the WHERE comparison matches zero students. Handle that empty term in the application.
- The average excludes Katherine because she has no enrollment row to group. Say that in the report so staff do not think every account was included.
- Repeating the same subquery in the select list and in WHERE is correct and redundant. A CTE names it once when the statement grows.
- SELECT * inside the subquery is unnecessary. Count the key you mean, which is the enrollment row.
- An UPDATE or DELETE without WHERE is a catastrophe. Do not "fix" the average by editing every enrollment. This lesson only reads.
Best Practices & Modern Standards
Use a scalar subquery when the English question is "greater than the average", and keep that subquery to one value. Correlate it on the primary key when the number belongs to the current student. Put the average in the select list when the reader needs to see the threshold beside the student. Alias every derived table.
When the same summary is used twice, or when a colleague must read the report, move it to a CTE. For a large users table, compare the subquery plan with a join and GROUP BY and keep the faster shape. Index enrollments.user_id so the correlated count is a range on an index, which the unique key in this sample already provides.
Real-World Use
Advisors ask which students are taking more courses than their peers. Students are users, the classes are courses, and each registration is an enrollment. The nested count is that student load, and the nested average is the peer load among students who have registered for at least one course. The office can then talk to Ada, who is above the average, without listing every enrollment on the summary page.
Frequently Asked Questions
Why is the average 2, and why is only Ada returned?
Ada has 3 courses, Grace has 2, and Alan has 1. The mean of those three counts is 2. The WHERE clause keeps counts strictly greater than the average, so only Ada remains. Grace is equal to the average, not above it.
Does Katherine affect the average?
No. The average groups rows in enrollments, and Katherine has none. She also fails the comparison because her count is 0, which is not greater than 2. Mention that limit when you explain the report to staff.
Why does the derived table need the alias per_user?
MySQL requires every derived table to have a name. per_user is that name, and course_count is the column the AVG reads. Omitting the alias is a syntax error.
Is a join faster than this subquery?
Often, once the student table is large, because the correlated count runs per row. The subquery is the clear form of the question. Check EXPLAIN, and move the summary into a join or a CTE when the plan shows a repeated scan.