Tsallaka zuwa abun ciki
Justice Tech School

Subqueries

A subquery is a SELECT inside another statement, written in parentheses. It can return a single value (to compare with), a list (to use with IN) or a table (to use in FROM). The inner query runs first.

Example
SELECT name, score
FROM students
WHERE score > (SELECT AVG(score) FROM students)
ORDER BY score DESC;

Result

name   | score
Ada    | 92
Zainab | 88
Amina  | 85
Kofi   | 78
Example
SELECT name
FROM students
WHERE id IN (SELECT student_id FROM enrolments WHERE course_id = 4)
ORDER BY name;

Result

name
Amina
Kofi
Zainab

Exercise

Compare with the average using a subquery.

SELECT * FROM students WHERE score > ( AVG(score) FROM students);

Quiz Test

Where is a subquery written?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.