Sub topic 8
EXISTS and NOT EXISTS
What you need first
This chapter assumes you can write a basic SELECT with WHERE, join two tables, and read a correlated subquery. A correlated subquery is an inner query that refers to a column of the outer query. The examples use the Oracle HR sample schema, mainly EMPLOYEES and DEPARTMENTS.
What EXISTS tests
EXISTS is a condition that takes a subquery. It is true if the subquery returns at least one row, and false if it returns none. It does not compare values, and it does not care what the rows contain.
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);For each row of departments, Oracle asks whether any employee row has the same department_id. If it does, the department is kept. The result is the departments that have at least one employee.
NOT EXISTS is the opposite. It is true when the subquery returns no rows.
SELECT d.department_name
FROM departments d
WHERE NOT EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);This lists departments with no employees. It is called an anti-join pattern: keep the rows from one table that have no match in another.
The select list is irrelevant
EXISTS only checks whether a row comes back, so the columns in the inner SELECT are never used. These three conditions behave the same:
WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department_id = d.department_id)
WHERE EXISTS (SELECT * FROM employees e WHERE e.department_id = d.department_id)
WHERE EXISTS (SELECT NULL FROM employees e WHERE e.department_id = d.department_id)Even SELECT NULL works, because the row exists even though its value is null. Most Oracle code uses SELECT 1 to show that no column is being read. Pick one style and use it consistently.
How evaluation works
Logically, Oracle evaluates the inner query once for each outer row. For each outer row it substitutes that row's correlated values (here d.department_id) into the inner query. It stops at the first matching row, because one row is enough to decide the result.
This describes the logic only. In practice the optimizer often rewrites an EXISTS subquery as a semi-join and a NOT EXISTS subquery as an anti-join. A later chapter covers that. The result is the same either way, so you can reason about correctness with the row-by-row model.
Adding conditions to the inner query
The inner query can have any WHERE conditions, not just the correlation. This finds departments that have at least one employee paid over 10000:
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id
AND e.salary > 10000);The correlation condition (e.department_id = d.department_id) links the inner row to the outer row. The other condition filters the inner rows. Keep these two roles clear in your head, because most EXISTS mistakes come from mixing them up.
You can also combine EXISTS and NOT EXISTS in the same query. This finds departments that have employees but nobody earning over 10000:
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id)
AND NOT EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id
AND e.salary > 10000);Why not just join?
A join returns one row per match. If you only want to know whether a match exists, the join can produce duplicates.
-- One row per employee, so a department appears many times.
SELECT d.department_name
FROM departments d
JOIN employees e ON e.department_id = d.department_id;
-- One row per department.
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);You can remove the duplicates from the join with DISTINCT, but that adds a sort or hash step, and it hides the intent. EXISTS states the intent directly: "keep each department that has an employee". The EXISTS query also never returns columns from the inner table, which is correct when you do not need them. If you do need inner columns, use a join.
EXISTS compared with IN
For the "at least one match" question, IN and EXISTS give the same rows.
SELECT d.department_name
FROM departments d
WHERE d.department_id IN (SELECT e.department_id FROM employees e);The differences matter mostly for the negated forms and for NULLs.
| Point | IN / NOT IN | EXISTS / NOT EXISTS |
|---|---|---|
| What it compares | A value against a set of values | Whether the subquery returns any row |
| Correlation | Usually not correlated | Almost always correlated |
| Comparisons beyond equality | Equality only | Any condition in the inner `WHERE` |
| Multiple columns | `(a, b) IN (...)` | Any number of conditions |
| NULL in the subquery result | `NOT IN` returns no rows | No effect, because the test is on row existence |
| Result of the test | True, false or unknown | True or false, never unknown |
The last two rows are the reason NOT EXISTS is the safer anti-join. A null in the subquery makes x NOT IN (...) unknown for every row, so nothing is returned. The next chapter covers this trap in detail. Here is the safe form for employees who manage nobody:
SELECT e.last_name
FROM employees e
WHERE NOT EXISTS (SELECT 1
FROM employees r
WHERE r.manager_id = e.employee_id);The equality r.manager_id = e.employee_id is false or unknown for rows where manager_id is null. Those rows simply do not count as matches. The inner query does not return them, and the outer row is kept when no match is found.
Common errors
Forgetting the correlation
If the inner query has no link to the outer query, EXISTS gives the same answer for every outer row.
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.salary > 10000);If any employee earns more than 10000, this returns every department. If none does, it returns no departments. The query runs without error, so the mistake is easy to miss. Whenever you write EXISTS, check that the inner query refers to an outer alias.
Not aliasing both tables in a self-reference
When the inner and outer queries use the same table, give them different aliases. Without aliases, an unqualified column name is resolved against the closest query block, which is the inner one. e.manager_id = e.employee_id compares two columns of the same row and is not a correlation.
Expecting inner columns in the result
An EXISTS subquery cannot contribute columns to the outer SELECT. The inner aliases are visible only inside the subquery. If you reference e.last_name in the outer select list, Oracle raises ORA-00904 (invalid identifier). Use a join when you need those columns.
Using NOT EXISTS where you need a join
NOT EXISTS tells you which outer rows have no match. It cannot show you what is missing. To list departments with no employees and also show the manager of each department, add columns from the outer table only, or use an outer join.
Writing DISTINCT to repair a join
If you find yourself writing SELECT DISTINCT after a join only to remove repeated outer rows, replace the join with EXISTS.
Rules of thumb
- Use
EXISTSfor "has at least one related row". UseNOT EXISTSfor "has no related row". - Prefer
NOT EXISTSoverNOT INwhenever the subquery column might contain nulls. - Put the link between the tables in the inner
WHERE, and put extra filters next to it. - Do not worry about performance of the select list.
SELECT 1andSELECT *cost the same.
Exercise
Write a query that returns the last names of employees who are managers, meaning at least one other employee has their employeeid as managerid. Use EXISTS.
Show answer
SELECT e.lastname FROM employees e WHERE EXISTS (SELECT 1 FROM employees r WHERE r.managerid = e.employee_id);
Exercise
A colleague writes SELECT department_name FROM departments d WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.salary > 100000). The query returns every department. What is wrong, and how do you fix it so that it returns departments in which nobody earns over 100000?
Show answer
The inner query has no correlation to the outer query, so the result is the same for every department. Because it returns no rows in this data (or the same answer for all), NOT EXISTS is true for every row. Add the correlation: WHERE e.departmentid = d.departmentid AND e.salary > 100000.