A subquery is a SELECT inside another query. It lets you use one result to answer a bigger question: “which students are above the average CGPA?” needs the average first. Subqueries can return a single value, a list for IN, a yes/no for EXISTS, or even a whole temporary table in FROM.
In this lesson you will learn
- Scalar subqueries that return one value
- Subqueries that return a list for
IN - Correlated subqueries that run once per row
EXISTSandNOT EXISTS- Subqueries in
FROM, and when a join is better
Single-Value and List Subqueries
-- Students above the average CGPA
SELECT name, cgpa FROM students
WHERE cgpa > (SELECT AVG(cgpa) FROM students)
ORDER BY cgpa DESC;
-- Students enrolled in Databases
SELECT name FROM students
WHERE id IN (SELECT student_id FROM enrollments WHERE course_id = 102);
Output
+--------+------+
| name | cgpa |
+--------+------+
| Tania | 3.95 |
| Nusrat | 3.82 |
| Mitu | 3.67 |
| Sabbir | 3.55 |
+--------+------+
(4 rows)
+--------+
| name |
+--------+
| Nusrat |
| Tania |
| Mitu |
+--------+
(3 rows)
(SELECT AVG(cgpa) FROM students)returns one number (3.5), and the outer query compares every row with it. This is a scalar subquery.id IN (SELECT student_id ...)uses a subquery that returns a list of ids. The outer query keeps students whose id is in that list.- The inner query runs first and does not depend on the outer one.
Correlated Subqueries, EXISTS and FROM
-- Each student's best mark (correlated subquery)
SELECT s.name,
(SELECT MAX(e.marks) FROM enrollments e WHERE e.student_id = s.id) AS best_mark
FROM students s
WHERE s.dept = 'CSE';
-- Departments that have at least one course
SELECT code, name FROM departments d
WHERE EXISTS (SELECT 1 FROM courses c WHERE c.dept = d.code);
-- Subquery in FROM: average of department averages
SELECT ROUND(AVG(avg_cgpa), 2) AS avg_of_depts
FROM (SELECT dept, AVG(cgpa) AS avg_cgpa FROM students GROUP BY dept);
Output
+--------+-----------+
| name | best_mark |
+--------+-----------+
| Nusrat | 92 |
| Tania | 95 |
| Mitu | 76 |
| Nadia | NULL |
+--------+-----------+
(4 rows)
+------+-------------------------+
| code | name |
+------+-------------------------+
| CSE | Computer Science |
| EEE | Electrical Engineering |
| BBA | Business Administration |
+------+-------------------------+
(3 rows)
+--------------+
| avg_of_depts |
+--------------+
| 3.44 |
+--------------+
(1 row)
- A correlated subquery refers to the outer row (
e.student_id = s.id), so it runs once for each student. Nadia has no marks, so her best mark isNULL. EXISTSis true as soon as the subquery finds any row. ME is missing from the result because it has no courses.SELECT 1is a convention; the selected value does not matter.- A subquery in
FROMacts as a temporary table (a derived table). Here it averages the three department averages.
Subquery or JOIN?
Many subqueries can be rewritten as joins, and the database often runs both the same way. Choose whichever reads more clearly. Subqueries suit questions like “compare with an overall value” or “does any related row exist?”; joins suit “show columns from both tables”. For long queries, a WITH clause (common table expression) gives a subquery a name:
WITH dept_avg AS (
SELECT dept, AVG(cgpa) AS avg_cgpa FROM students GROUP BY dept
)
SELECT * FROM dept_avg WHERE avg_cgpa > 3.3;
Common Mistakes
- A scalar subquery that returns several rows, used with
=. UseIN, or make sure it returns one value. NOT INwith a list containingNULL, which returns no rows at all.NOT EXISTSavoids this trap.- Forgetting the brackets around a subquery.
Practice Exercises
Exercise 1. Find the student or students with the highest CGPA.
Show answer
SELECT name, cgpa FROM students
WHERE cgpa = (SELECT MAX(cgpa) FROM students); -- Tania 3.95
Exercise 2. List departments that have no students, using NOT EXISTS.
Show answer
SELECT code FROM departments d
WHERE NOT EXISTS (SELECT 1 FROM students s WHERE s.dept = d.code); -- ME
Frequently Asked Questions
Are correlated subqueries slow?
They can be, because they conceptually run once per outer row. Modern optimisers often rewrite them as joins; check with the query plan if performance matters.
Can I use a subquery in UPDATE or DELETE?
Yes, for example DELETE FROM enrollments WHERE student_id IN (SELECT id FROM students WHERE dept = 'BBA');
Summary
- A subquery is a query inside another, always in brackets.
- Scalar subqueries return one value;
INsubqueries return a list. - Correlated subqueries refer to the outer row;
EXISTSchecks for any match. WITHnames a subquery so long queries stay readable.
Next: CREATE TABLE and Constraints.
