# EXISTS vs IN in SQL

Source: https://sqlstreak.com/sql/exists-vs-in · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** `IN` compares a value against a list from a subquery; `EXISTS` asks whether a correlated subquery returns any row. They give the same answer for matches. With `NOT`, they differ: if the list contains a NULL, `NOT IN` returns no rows at all, while `NOT EXISTS` behaves as you'd expect.

## Side by side

| | EXISTS | IN |
| --- | --- | --- |
| Checks | Does the subquery return any row? | Is the value in the subquery's list? |
| The subquery | Refers to the outer row (correlated) | Runs on its own, returns one column |
| NULL in the list, with NOT | Unaffected | NOT IN returns no rows |
| Reads best for | “has at least one related row” | a short list of values |

## Examples

### IN: customers with a cancelled order

```sql
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'cancelled')
ORDER BY name;
```

Result (both engines):

| name |
| --- |
| Priya Nair |
| Tomás Herrera |

### EXISTS: the same customers

```sql
SELECT name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o
              WHERE o.customer_id = c.id AND o.status = 'cancelled')
ORDER BY name;
```

Result (both engines):

| name |
| --- |
| Priya Nair |
| Tomás Herrera |

### The NOT IN trap

Staff who manage nobody. The owner's `manager_id` is NULL, so the list contains a NULL, and `NOT IN` can't be sure about anyone: no rows at all.

```sql
SELECT name
FROM staff
WHERE id NOT IN (SELECT manager_id FROM staff);
```

PostgreSQL:

| name |
| --- |

SQLite:

|  |
|  |

### NOT EXISTS gets it right

```sql
SELECT name
FROM staff s
WHERE NOT EXISTS (SELECT 1 FROM staff r WHERE r.manager_id = s.id)
ORDER BY name;
```

Result (both engines):

| name |
| --- |
| Ben Carter |
| Ivan Petrov |
| Noah Kim |
| Yuki Tanaka |
| Zara Ali |

## When to use which

- **EXISTS:** “Has at least one related row” checks, and every NOT version: NOT EXISTS is never caught out by NULLs.
- **IN:** A fixed list (`IN ('cat', 'dog')`) or a simple subquery whose column can't be NULL.

## Common mistakes

- `NOT IN` against a column that can be NULL: one NULL makes the whole result empty. Use NOT EXISTS, or add `WHERE manager_id IS NOT NULL` inside.
- Returning two columns from an IN subquery: it must return exactly one.
- Forgetting to correlate the EXISTS subquery (`WHERE o.customer_id = c.id`): without it, EXISTS is true for every row whenever any order exists.
