Reading history

SQL Subqueries: Scalar, IN, EXISTS and Correlated

4 min read 1 views

Learn SQL subqueries: single-value and IN subqueries, correlated subqueries, EXISTS and NOT EXISTS, derived tables and WITH (CTE).

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
  • EXISTS and NOT 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 is NULL.
  • EXISTS is true as soon as the subquery finds any row. ME is missing from the result because it has no courses. SELECT 1 is a convention; the selected value does not matter.
  • A subquery in FROM acts 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

  1. A scalar subquery that returns several rows, used with =. Use IN, or make sure it returns one value.
  2. NOT IN with a list containing NULL, which returns no rows at all. NOT EXISTS avoids this trap.
  3. 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; IN subqueries return a list.
  • Correlated subqueries refer to the outer row; EXISTS checks for any match.
  • WITH names a subquery so long queries stay readable.

Next: CREATE TABLE and Constraints.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *