Subqueries and Common Table Expressions
💻 SQLUse a query inside another query, and make complex reports readable with WITH.
0 of 9 completed
Sometimes the answer to one question is needed to ask the next. Subqueries and CTEs let you build that step by step.
By the end of this lesson you can:
- Use a subquery in WHERE.
- Use a subquery in FROM.
- Write a common table expression.
Subquery in WHERE
Compare a value against the result of another query.
SELECT name, score
FROM students
WHERE score > (SELECT AVG(score) FROM students);Subquery with IN
Use IN when the inner query returns a list.
SELECT name
FROM students
WHERE id IN (
SELECT student_id
FROM enrolments
WHERE course_id = 3
);Common Table Expressions
A CTE names a temporary result with WITH. It is easier to read than nesting three subqueries and can be referenced more than once.
WITH level_averages AS (
SELECT level, AVG(score) AS average_score
FROM students
GROUP BY level
)
SELECT level, average_score
FROM level_averages
WHERE average_score > 60;Tip If a query has three levels of nesting, rewrite it with CTEs. Future you will thank present you.
Practice
- Find students scoring above the class average.
- List courses that have at least one enrolment.
- Rewrite a nested query using WITH.
Hands-on exercise
Write a query that returns students who scored above the average for their own level.
Use a CTE that computes the average score per level.
Recap
Subqueries answer one question inside another. CTEs name the steps so complex reports stay readable.
Example
SELECT name, score
FROM students
WHERE score > (SELECT AVG(score) FROM students);
Exercises
Exercise 1. Above average by level
Hard
Write a query that returns students who scored above the average for their own level.
Use a CTE that computes the average score per level.
Use a CTE that computes the average score per level.
SQL
exercise-1.sql
Output
Expected Output
Each student appears only when their score beats their level average.
Lesson Nav
Course contents
SQL Course
0/9 lessons completed
- 1 What a Database Is Tutorial
- 2 Filtering and Sorting Tutorial
- 3 Aggregates and Grouping Tutorial
- 4 Joining Tables Tutorial
- 5 Subqueries and Common Table Expressions Tutorial
- 6 Inserting, Updating and Deleting Tutorial
- 7 Schemas, Keys and Normalisation Tutorial
- 8 Indexes and Query Performance Tutorial
- 9 Project: A Reporting Query Project
Exercises
Exercise 1 Above average by level