Stop 03 · Filtering DataTopics · 4/8

IN and NOT IN

Part of the SQL Roadmap

In short

When a column can match any of several values, chaining ORs gets long fast. IN takes a list and checks membership in one go. NOT IN does the opposite, with one nasty trap.

IN checks whether a value matches any item in a list, which is shorter than chaining ORs. NOT IN has a trap: if the list contains a NULL, it returns no rows at all.

The jaadu, dressed as a guard at a decorated wedding gate, runs a finger down a long paper guest list while guests wait.

Think of it like this

The wedding guest list

The guard at the shaadi gate has a printed list. Is your name on it? You're in. That's IN. NOT IN is a "do not admit" list. But if one line of that list is smudged and unreadable, a careful guard won't let anyone in, because any guest might be the smudged name. That's the NULL trap.

Watch it happen

city IN ('Pune', 'Nagpur', 'Nashik')

Pune
0
Mumbai
1
Nashik
2
Delhi
3
Nagpur
4
Pune
5

1/5Each row's city is checked against the list of three.

The big ideas

What you need to know

IN is a short OR

city IN ('Pune', 'Nagpur') means city = 'Pune' OR city = 'Nagpur'.

NOT IN excludes

status NOT IN ('cancelled', 'returned') keeps every other status, but also drops rows where status is NULL.

The NULL trap

If the NOT IN list contains a NULL, the result is empty. This bites hardest with subqueries.

Lists from subqueries

IN (SELECT customer_id FROM vip_customers) builds the list from another table. For NOT, prefer NOT EXISTS.

See it in code

Walk through the code

sql
1SELECT order_id, city2FROM orders3WHERE city IN ('Pune', 'Nagpur', 'Nashik');4 5SELECT order_id, status6FROM orders7WHERE status NOT IN ('cancelled', 'returned');8 9-- Customers who never ordered: safe even if NULLs exist10SELECT c.customer_id, c.name11FROM customers c12WHERE NOT EXISTS (13  SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id14);

1/3Orders from three Maharashtra cities.

IN and NOT IN with fixed lists, then the NULL-safe way to exclude using another table. All run in PostgreSQL and MySQL.

Save yourself the pain

Common mistakes

Oops

WHERE customer_id NOT IN (SELECT customer_id FROM orders) when orders.customer_id can be NULL.

Do this instead

Use NOT EXISTS, or add WHERE customer_id IS NOT NULL inside the subquery.

Oops

Writing a long chain of OR conditions on the same column.

Do this instead

Use IN. It's shorter and easier to edit.

Your mission

Lists in and out

~20 min

Quick check

What does WHERE id NOT IN (1, 2, NULL) return?

Go deeper

  1. 1Replace a chain of OR conditions with a single IN list.
  2. 2Test NOT IN (1, 2, NULL) and see that it returns nothing.
  3. 3Prefer NOT EXISTS over NOT IN when the list comes from a subquery that might contain NULLs.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge