Reading history

SQL EXISTS and NOT EXISTS: Semi-Joins and Anti-Joins

5 min read 0 views

Learn SQL EXISTS and NOT EXISTS with correlated subqueries: find rows with or without a match, and avoid the NOT IN trap with NULL values.

“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 EXISTS works with a correlated subquery
  • Semi-joins: rows that have a match
  • Anti-joins: rows that have no match
  • Why NOT IN fails when the list contains NULL
  • When to choose EXISTS, IN or a JOIN

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)
studentsenrollments (student_id)1 Nusrat2 Arif3 Tania4 Imran5 Mitu6 Rafi7 Sabbir8 Nadia113352647EXISTS (semi-join)has at least one matchlisted once: 7 studentsNOT EXISTS (anti-join)has no match at allonly Nadia
  • 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 EXISTS efficient.

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?

GoalGood choice
Rows that have a match, no duplicatesEXISTS or IN
Rows that have no matchNOT EXISTS (safe with NULL), or LEFT JOIN … WHERE right.id IS NULL
Need columns from the other tableJOIN
Short fixed list of valuesIN ('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

  1. Using NOT IN with a column that can be NULL. One NULL makes the result empty.
  2. Forgetting the correlation. EXISTS (SELECT 1 FROM enrollments) without WHERE e.student_id = s.id is true for every student as long as the table has any row.
  3. Using a JOIN to test for existence. It repeats rows when there are several matches; you then need DISTINCT.
  4. Selecting columns inside EXISTS for no reason. They are ignored; SELECT 1 shows 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

  • EXISTS is true when the subquery finds at least one row.
  • Semi-joins keep matched rows once; anti-joins keep unmatched rows.
  • NOT IN returns nothing if its list contains NULL; prefer NOT EXISTS.
  • Use a join only when you need columns from the other table.

Next: SQL LAG and LEAD: Compare Rows.

Lessons are also marked complete when you click Next.

Leave a Reply

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