Subqueries and CTEs for Beginners, in One Place
Once you are comfortable with SELECT and JOIN, you will meet queries inside queries. They look intimidating, but they are just a way of answering a question in two steps. This free guide covers subqueries and common table expressions (CTEs) gently.
The practice tables
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE scores (
student_id INTEGER REFERENCES students(id),
subject TEXT NOT NULL,
score INTEGER NOT NULL
);
Add a few students and scores of your own.
Idea 1: a subquery returns one value
Question: who scored above the average maths score?
Step one, the average:
SELECT AVG(score) FROM scores WHERE subject = 'maths';
Step two, use it inside another query:
SELECT student_id, score
FROM scores
WHERE subject = 'maths'
AND score > (SELECT AVG(score) FROM scores WHERE subject = 'maths');
The part in brackets is a subquery. The database works it out and uses the result like a number.
Idea 2: a subquery returns a list, with IN
Question: which students have at least one score above 90?
SELECT name FROM students
WHERE id IN (SELECT student_id FROM scores WHERE score > 90);
Idea 3: EXISTS asks "is there any?"
The same question, written with EXISTS:
SELECT name FROM students s
WHERE EXISTS (
SELECT 1 FROM scores sc WHERE sc.student_id = s.id AND sc.score > 90
);
EXISTS stops looking as soon as it finds one match. NOT EXISTS finds students with no such score, which is often clearer than other approaches.
Idea 4: CTEs give steps a name
A common table expression uses WITH to name a step, then uses it like a table:
WITH maths_avg AS (
SELECT AVG(score) AS avg_score FROM scores WHERE subject = 'maths'
)
SELECT sc.student_id, sc.score
FROM scores sc, maths_avg
WHERE sc.subject = 'maths' AND sc.score > maths_avg.avg_score;
It does the same job as Idea 1, but reads from top to bottom like a recipe. CTEs are supported by SQLite, PostgreSQL, SQL Server and MySQL 8.0.
Choosing between them
| Situation | Reach for |
|---|---|
| Compare with one calculated value | Subquery in WHERE |
| Match against a list | IN with a subquery |
| "Has any" or "has none" | EXISTS or NOT EXISTS |
| Several steps that build on each other | CTEs |
| Combining columns from two tables | Usually a JOIN instead |
Common beginner mistakes
- A subquery that returns several values where one is expected.
score > (SELECT score FROM scores)fails if there is more than one row. - NOT IN with NULLs. If the subquery's list contains a NULL,
NOT INcan return no rows at all. NOT EXISTS avoids this surprise. - Forgetting the link in EXISTS. Without
sc.student_id = s.id, the inner query checks the whole table, not the current student.
Practise
Rewrite each idea above against a sample database such as one listed on our sample databases page. Then try writing the same question two ways and check both give the same answer.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.
This page is a free outline. No downloadable files, paid content, courses or certificates are offered on this site.