“Which students have enrolled in at least one course?” and “Which customers have never ordered?” are yes-or-no questions about another table. SQL answers them with EXISTS and NOT EXISTS. They are fast, they never create duplicate rows, and NOT EXISTS avoids a famous trap with NOT IN and NULL values that silently returns no rows at all.
In this lesson you will learn
- How
EXISTSworks with a correlated subquery - Semi-joins: rows that have a match
- Anti-joins: rows that have no match
- Why
NOT INfails when the list contains NULL - When to choose
EXISTS,INor aJOIN
You should know subqueries, joins and NULL values.
EXISTS and NOT EXISTS
EXISTS (subquery) is true if the subquery returns at least one row. The subquery is usually correlated: it refers to the outer row, here through s.id. What the subquery selects does not matter, so people write SELECT 1.
-- Students who are enrolled in at least one course (semi-join)
SELECT s.name, s.dept
FROM students AS s
WHERE EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.id);
-- Students with no enrollment at all (anti-join)
SELECT s.name, s.dept
FROM students AS s
WHERE NOT EXISTS (SELECT 1 FROM enrollments AS e WHERE e.student_id = s.id);
Output
+--------+------+
| name | dept |
+--------+------+
| Nusrat | CSE |
| Arif | EEE |
| Tania | CSE |
| Imran | BBA |
| Mitu | CSE |
| Rafi | EEE |
| Sabbir | BBA |
+--------+------+
(7 rows)
+-------+------+
| name | dept |
+-------+------+
| Nadia | CSE |
+-------+------+
(1 row)
- The first query is a semi-join: it keeps students who have a match. Nusrat has two enrollments but still appears once, unlike a normal
JOIN, which would list her twice. - The second is an anti-join: it keeps students with no match. Only Nadia has never enrolled.
- The database can stop searching as soon as it finds one matching row, which makes
EXISTSefficient.
The NOT IN and NULL Trap
-- A list of "blocked" customers; one row has a missing name
CREATE TABLE blocked (customer TEXT);
INSERT INTO blocked VALUES ('Tuhin'), (NULL);
-- Customers NOT IN the blocked list: returns nothing!
SELECT DISTINCT customer FROM orders
WHERE customer NOT IN (SELECT customer FROM blocked);
-- NOT EXISTS handles the NULL safely
SELECT DISTINCT o.customer FROM orders AS o
WHERE NOT EXISTS (SELECT 1 FROM blocked AS b WHERE b.customer = o.customer);
Output
+----------+
| customer |
+----------+
+----------+
(0 rows)
+----------+
| customer |
+----------+
| Karim |
| Rina |
| Joya |
+----------+
(3 rows)
The NOT IN query returns nothing, even though Karim, Rina and Joya are clearly not blocked. The reason is NULL. For Karim, SQL checks 'Karim' <> 'Tuhin' AND 'Karim' <> NULL. Any comparison with NULL is unknown, so the whole condition is unknown, and the row is dropped. One NULL in the list removes every row.
NOT EXISTS does not have this problem: the NULL row simply never matches, so it is ignored. If you must use NOT IN, filter the list: NOT IN (SELECT customer FROM blocked WHERE customer IS NOT NULL).
EXISTS, IN or JOIN?
| Goal | Good choice |
|---|---|
| Rows that have a match, no duplicates | EXISTS or IN |
| Rows that have no match | NOT EXISTS (safe with NULL), or LEFT JOIN … WHERE right.id IS NULL |
| Need columns from the other table | JOIN |
| Short fixed list of values | IN ('CSE', 'EEE') |
Modern databases often run EXISTS, IN and the equivalent join with the same plan, so choose the one that states your meaning most clearly.
Common Mistakes
- Using
NOT INwith a column that can be NULL. One NULL makes the result empty. - Forgetting the correlation.
EXISTS (SELECT 1 FROM enrollments)withoutWHERE e.student_id = s.idis true for every student as long as the table has any row. - Using a JOIN to test for existence. It repeats rows when there are several matches; you then need
DISTINCT. - Selecting columns inside EXISTS for no reason. They are ignored;
SELECT 1shows your intent.
Practice Exercises
Exercise 1. List the departments that have no students.
Show answer
SELECT d.name
FROM departments AS d
WHERE NOT EXISTS (SELECT 1 FROM students AS s WHERE s.dept = d.code);
Only Mechanical Engineering has no students.
Exercise 2. List courses in which at least one student scored 90 or more.
Show answer
SELECT c.title
FROM courses AS c
WHERE EXISTS (SELECT 1 FROM enrollments AS e
WHERE e.course_id = c.id AND e.marks >= 90);
Data Structures (Tania 95) and Databases (Nusrat 92, Tania 90).
Frequently Asked Questions
Is EXISTS faster than IN?
Sometimes, on older databases or very large subqueries, but modern optimizers usually treat them the same. The bigger difference is correctness: NOT EXISTS is safe with NULL values and NOT IN is not.
Does SELECT * inside EXISTS slow the query down?
No. The database only checks whether a row exists and never fetches the selected columns, so SELECT *, SELECT 1 and SELECT NULL behave the same.
Summary
EXISTSis true when the subquery finds at least one row.- Semi-joins keep matched rows once; anti-joins keep unmatched rows.
NOT INreturns nothing if its list contains NULL; preferNOT EXISTS.- Use a join only when you need columns from the other table.
