SQL · Module 8 · Lesson 31 min read

EXISTS, IN, ANY/ALL & the NOT IN Trap

IN

x IN (subquery) – true if x equals any value in the list.

EXISTS

EXISTS (subquery) – true if the subquery returns at least one row. The selected columns don't matter, so we write SELECT 1. It stops at the first match (efficient).

⚠️ The NOT IN + NULL trap

x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL. x <> NULL is unknown, so the whole expression is never true → zero rows, with no error.

SQL
SELECT name FROM users
WHERE id NOT IN (SELECT referred_by FROM users);  -- returns NOTHING

because referred_by contains NULLs (Asha and Hari weren't referred).

Safe alternatives

  • NOT EXISTS (… WHERE correlated condition) ✅ unaffected by NULLs
  • Filter NULLs out: NOT IN (SELECT referred_by FROM users WHERE referred_by IS NOT NULL)
  • LEFT JOIN … WHERE right.id IS NULL

ANY / SOME and ALL

Compare with a list using any operator:

  • amount > ANY (subquery) – greater than at least one value (> the minimum)
  • amount > ALL (subquery) – greater than every value (> the maximum)
  • = ANY(…) is the same as IN; <> ALL(…) is the same as NOT IN (with the same NULL trap)
  • PostgreSQL arrays: 'social' = ANY(tags), user_id = ANY(ARRAY[1, 2, 3])

Which should I use?

GoalBest choice
Value in a small fixed listIN ('a', 'b')
Has related rowsEXISTS
Has NO related rowsNOT EXISTS ✅
Compare with all/any valuesALL / ANY
Element in an array column= ANY(array)

Example

SQL
-- Who has referred someone? (IN)
SELECT name FROM users
WHERE id IN (SELECT referred_by FROM users);
-- Asha, Ravi, Sita

-- ⚠️ The trap: who has NOT referred anyone? NOT IN returns nothing!
SELECT name FROM users
WHERE id NOT IN (SELECT referred_by FROM users);
-- (0 rows)  ← because the list contains NULLs

-- ✅ NOT EXISTS is NULL-safe
SELECT name FROM users u
WHERE NOT EXISTS (SELECT 1 FROM users x WHERE x.referred_by = u.id);
-- Bikash, Maya, Hari

-- ✅ Or remove the NULLs explicitly
SELECT name FROM users
WHERE id NOT IN (SELECT referred_by FROM users WHERE referred_by IS NOT NULL);

-- See the logic directly
SELECT 3 NOT IN (1, 2)        AS clean_list,    -- true
       3 NOT IN (1, 2, NULL)  AS with_null;     -- NULL (unknown)

-- ALL: expenses bigger than every one of Bikash's expenses
SELECT title, amount FROM expenses
WHERE amount > ALL (SELECT amount FROM expenses WHERE user_id = 4)
ORDER BY amount;

-- ANY with arrays
SELECT title, tags FROM expenses WHERE 'travel' = ANY(tags);
SELECT name FROM users WHERE id = ANY(ARRAY[1, 3, 5]);