In this post we are going to cover IN and NOT IN in Snowflake, and the one thing about NOT IN that catches almost everybody out.
IN asks whether our value is one of a list of values. We can type that list out ourselves, or we can let a query produce it. NOT IN is supposed to be the opposite of that.
We will start with a list and a simple IN. Then we will change one word to NOT IN and watch a correct query come back with nothing at all. We will work out why, fix it three different ways, and finish by checking whether IN itself is still safe to use.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 38 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with IN, and let a query build the list
- Now let's flip it to NOT IN
- Let's work out why the whole result vanished
- Can we blame the subquery? Let's find out
- Now let's fix it, three different ways
- Can we still trust IN? Let's check
- One last thing: what to do about this on Monday
Let's create some sample data
We need two tables for this one. DEPARTMENTS holds the departments that exist. EMPLOYEES holds a DEPT_ID on each person, saying which department they are in.
Copy the script below into a worksheet and run it once. Read the two INSERT lists while you are there, because everything on this page comes out of what is in them.
-- The two tables this episode compares. EMPLOYEES comes from Episode 1 and
-- DEPARTMENTS from Episode 24; both are reproduced here, because the trap below
-- depends on exactly which DEPT_ID values each one holds.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE DEPARTMENTS (
DEPT_ID INT,
DEPT_NAME VARCHAR,
LOCATION VARCHAR,
BUDGET NUMBER(12,2)
);
INSERT INTO DEPARTMENTS VALUES
(10, 'Engineering', 'Charlotte', 2400000.00),
(20, 'Finance', 'Charlotte', 1100000.00),
(30, 'Marketing', 'Raleigh', 750000.00),
(40, 'Operations', 'Raleigh', 640000.00);
CREATE OR REPLACE TABLE EMPLOYEES (
EMP_ID INT,
FIRST_NAME VARCHAR,
LAST_NAME VARCHAR,
EMAIL VARCHAR,
DEPT_ID INT,
MANAGER_ID INT,
SALARY NUMBER(10,2),
COMMISSION_PCT NUMBER(4,2),
HIRE_DATE DATE
);
-- Look at the DEPT_ID column. Grace, on the last line, is the row this whole
-- episode turns on: her DEPT_ID is NULL.
INSERT INTO EMPLOYEES VALUES
(1, 'Aisha', 'Khan', 'aisha.khan@example.com', 10, 6, 118000.00, NULL, '2019-03-11'),
(2, 'Marcus', 'Reid', 'marcus.reid@example.com', 10, 6, 96500.00, NULL, '2021-07-01'),
(3, 'Lena', 'Fischer', 'lena.fischer@example.com', 20, 6, 104000.00, 0.05, '2018-01-22'),
(4, 'Tomas', 'Novak', 'tomas.novak@example.com', 20, 3, 87250.00, NULL, '2022-09-05'),
(5, 'Priya', 'Raman', 'priya.raman@example.com', 30, 6, 96500.00, 0.10, '2020-11-17'),
(6, 'Daniel', 'O''Connor', 'daniel.oconnor@example.com', 10, NULL, 131000.00, NULL, '2016-05-30'),
(7, 'Sofia', 'Marino', 'sofia.marino@example.com', 30, 5, 71400.00, 0.08, '2023-02-13'),
(8, 'Grace', 'Lin', 'grace.lin@example.com', NULL, 6, 92000.00, NULL, '2021-04-19');DEPARTMENTS has four departments: 10, 20, 30 and 40. Nobody works in 40, Operations. That is the fact we are going to try to find with a query.
Now let's look at the other side. Which DEPT_ID values does EMPLOYEES actually hold?
SELECT DISTINCT DEPT_ID FROM EMPLOYEES ORDER BY DEPT_ID NULLS LAST;| DEPT_ID |
|---|
| 10 |
| 20 |
| 30 |
| NULL |
10, 20, 30, and then a NULL. The NULL is Grace, who has no department. DEPT_ID is nullable, nobody did anything wrong, and there is nothing in that grid anyone would look twice at.
Remember that the NULL is in the list. That is the whole post. Everything that follows is correct SQL giving us a wrong answer because of it.
Let's start with IN, and let a query build the list
IN asks one question. Is my value one of these? We can write the list out by hand, or we can let a query produce it. The query form is the useful one, because then the list is whatever the data says today rather than whatever we typed last year.
So let's ask which departments have somebody in them.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID IN (SELECT DEPT_ID FROM EMPLOYEES)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 10 | Engineering |
| 20 | Finance |
| 30 | Marketing |
Three rows. Engineering, Finance and Marketing all have staff. Operations is not in the grid, and that is right, because no employee points at 40.
Now let's type the same list out by hand and run it again. We want this one on the page so we have something to compare against later.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID IN (10, 20, 30)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 10 | Engineering |
| 20 | Finance |
| 30 | Marketing |
The same three rows. So IN behaves the way it reads, with a subquery or without one, and the NULL in the list has caused us no trouble at all.
Now let's flip it to NOT IN
Let's ask the opposite question. Which departments have nobody in them? Same outer query, same subquery, one word changed.
We already know the answer. It is 40, Operations. It was the one department missing from the IN result we just ran.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID NOT IN (SELECT DEPT_ID FROM EMPLOYEES)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|
Nothing came back. No error. No warning. No NULL in an output column to hint at what happened. The statement succeeded, and what it told us is that there are no empty departments. Department 40 is sitting in the INSERT script we ran at the top of this page.
That is what makes this one dangerous. A query that errors gets fixed. A query that comes back empty gets read as there is nothing to report, and that is a perfectly ordinary thing for a report to say.
Let's add one condition and run it again
We are going to change one thing. A single predicate goes inside the subquery. The outer query stays the same, the data stays the same, the operator stays the same.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID NOT IN (SELECT DEPT_ID FROM EMPLOYEES WHERE DEPT_ID IS NOT NULL)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 40 | Operations |
40, Operations. The only difference between this query and the empty one is WHERE DEPT_ID IS NOT NULL inside the brackets. So the NULL is the cause. We did not argue our way to that. We swapped one line and watched the answer come back.
Let's work out why the whole result vanished
NOT IN is not a single operator that looks down a list. It is shorthand for a chain of inequalities joined by AND.
| What you write | What it means |
|---|---|
x IN (a, b, c) | x = a OR x = b OR x = c |
x NOT IN (a, b, c) | x <> a AND x <> b AND x <> c |
So let's take Operations, department 40, and test it against the list 10, 20, 30, NULL. The condition becomes four comparisons. Rather than tell you what they come out as, let's get Snowflake to evaluate every one of them, and both AND chains, in a single row.
SELECT 40 <> 10 AS "40 <> 10",
40 <> 20 AS "40 <> 20",
40 <> 30 AS "40 <> 30",
40 <> NULL AS "40 <> NULL",
(40 <> 10 AND 40 <> 20 AND 40 <> 30) AS WITHOUT_THE_NULL,
(40 <> 10 AND 40 <> 20 AND 40 <> 30 AND 40 <> NULL) AS WITH_THE_NULL;| 40 <> 10 | 40 <> 20 | 40 <> 30 | 40 <> NULL | WITHOUT_THE_NULL | WITH_THE_NULL |
|---|---|---|---|---|---|
| TRUE | TRUE | TRUE | NULL | TRUE | NULL |
The first three comparisons are TRUE. The fourth one is NULL. Comparing anything to NULL does not give us TRUE and does not give us FALSE. NULL means no value is recorded here, so there is no way to know whether that unrecorded value is 40. The answer is unknown.
The last two columns are the two chains side by side. WITHOUT_THE_NULL is TRUE, so department 40 qualifies. WITH_THE_NULL is NULL, so it does not. TRUE AND UNKNOWN is UNKNOWN, and a WHERE clause keeps only the rows whose condition came out TRUE. Unknown is not true.
That explains one row. Now let's see why every row goes
What we just read covers a department that is not in the list, and there is only one of those. The other three go for a different reason. We need both reasons to account for a grid that comes back completely empty.
| Department | First comparisons | <> NULL | Whole condition | Kept? |
|---|---|---|---|---|
40 — not in the list | all TRUE | UNKNOWN | TRUE AND UNKNOWN → UNKNOWN | No — wrongly |
10, 20, 30 — in the list | one is FALSE | UNKNOWN | FALSE AND UNKNOWN → FALSE | No — correctly |
A department that is in the list fails its own inequality. FALSE AND anything is FALSE, so it is dropped for the right reason. A department that is not in the list can only ever get to UNKNOWN, so it is dropped for the wrong one. Between them that is every row in the table.
With a NULL anywhere in the list, NOT IN cannot return a single row. Not one, ever, for any data. It is not that the answer is incomplete or that some edge case was missed. The condition is incapable of coming out TRUE, so the result is empty by construction.
Can we blame the subquery? Let's find out
It would be easy to walk away from this blaming subqueries. Something about the brackets, or the inner query, or how Snowflake builds the list. So let's take the subquery out completely and type the list by hand, with the NULL written into it.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID NOT IN (10, 20, 30, NULL)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|
The same empty grid. Now let's take the NULL out of that typed list and leave everything else exactly as it is.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID NOT IN (10, 20, 30)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 40 | Operations |
40, Operations. So the subquery was never the problem. It was only how the NULL got into the list without anybody typing it. This is about NULL, and about NOT IN.
A subquery does make it much harder to spot, though. A typed list is right there in the query text, so a NULL sitting in it is at least readable. A subquery's list is whatever the data holds today, and a nullable column can start producing a NULL years after the query was written and reviewed.
Now let's fix it, three different ways
We have seen the first fix already. Exclude the NULLs inside the subquery with WHERE DEPT_ID IS NOT NULL. It works, and it is the smallest change we can make. It also only protects the one query we remembered to put it in.
The second fix is NOT EXISTS. It asks whether a matching row exists, instead of comparing our value against a list.
SELECT D.DEPT_ID, D.DEPT_NAME
FROM DEPARTMENTS D
WHERE NOT EXISTS (SELECT 1 FROM EMPLOYEES E WHERE E.DEPT_ID = D.DEPT_ID)
ORDER BY D.DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 40 | Operations |
40, Operations. NOT EXISTS cannot fall into this. The comparison E.DEPT_ID = D.DEPT_ID is unknown for Grace's row, so her row does not match, and a row that does not match simply does not contribute to the existence test. There is no AND chain for an unknown to travel through.
The third fix is an anti-join, which we covered in Episode 25. Keep every department with a LEFT JOIN, then keep only the ones where the employee side came back empty.
SELECT D.DEPT_ID, D.DEPT_NAME
FROM DEPARTMENTS D
LEFT JOIN EMPLOYEES E ON E.DEPT_ID = D.DEPT_ID
WHERE E.EMP_ID IS NULL
ORDER BY D.DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 40 | Operations |
40 again. The join condition is unknown for Grace too, so she matches no department and the NULL never reaches the filter.
Let's count all four approaches in one result
SELECT
(SELECT COUNT(*) FROM DEPARTMENTS
WHERE DEPT_ID NOT IN (SELECT DEPT_ID FROM EMPLOYEES)) AS NOT_IN,
(SELECT COUNT(*) FROM DEPARTMENTS
WHERE DEPT_ID NOT IN (SELECT DEPT_ID FROM EMPLOYEES
WHERE DEPT_ID IS NOT NULL)) AS NOT_IN_FILTERED,
(SELECT COUNT(*) FROM DEPARTMENTS D
WHERE NOT EXISTS (SELECT 1 FROM EMPLOYEES E
WHERE E.DEPT_ID = D.DEPT_ID)) AS NOT_EXISTS,
(SELECT COUNT(*) FROM DEPARTMENTS D
LEFT JOIN EMPLOYEES E ON E.DEPT_ID = D.DEPT_ID
WHERE E.EMP_ID IS NULL) AS ANTI_JOIN;| NOT_IN | NOT_IN_FILTERED | NOT_EXISTS | ANTI_JOIN |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
NOT IN says there are no empty departments. The other three all say there is one. Three different techniques agree and NOT IN is the odd one out. That is not a disagreement about style. It is a wrong answer.
| Approach | Safe with NULLs? | Worth knowing |
|---|---|---|
NOT IN (subquery) | No | Returns nothing at all if the list contains one NULL |
NOT IN (... IS NOT NULL) | Yes | Correct, minimal, and easy to leave out of the next query |
NOT EXISTS | Yes | Immune by construction; reads as the question being asked |
Anti-join — LEFT JOIN + IS NULL | Yes | Immune, and gives you the other side's columns if you need them |
Can we still trust IN? Let's check
The wrong lesson to take from all this is that NULLs break IN. They do not. Let's run the positive form with a NULL sitting in the list.
SELECT DEPT_ID, DEPT_NAME
FROM DEPARTMENTS
WHERE DEPT_ID IN (10, 20, NULL)
ORDER BY DEPT_ID;| DEPT_ID | DEPT_NAME |
|---|---|
| 10 | Engineering |
| 20 | Finance |
Two rows, Engineering and Finance, exactly what we wanted. IN expands to OR rather than AND, and that is the whole difference. TRUE OR UNKNOWN is TRUE, so an unknown comparison sitting next to a matching one changes nothing. NULL never matches anything, so IN just does not find it, and no harm is done.
| Chain | With one unknown in it | Effect on the row |
|---|---|---|
OR — what IN builds | TRUE OR UNKNOWN → TRUE | A match still wins. Harmless. |
AND — what NOT IN builds | TRUE AND UNKNOWN → UNKNOWN | The unknown wins. Nothing qualifies. |
So it is only the negative form that collapses, and it collapses because of the way AND treats unknown. IN is fine. NOT IN is the one to watch.
One last thing: what to do about this on Monday
This trap is not rare and it is not exotic. It needs three ordinary things: a nullable column, a NOT IN against it, and nobody checking whether an empty result is the truth.
- Treat an empty result from
NOT INas a question, not an answer. Run the subquery on its own and look for aNULLbefore you believe the outer query. - Reach for
NOT EXISTSor an anti-join by default. Both are immune without anybody having to remember a guard clause, and the anti-join hands you the other table's columns as well. - If you do keep
NOT IN, put theIS NOT NULLin the subquery even when the column is not nullable today. A column's nullability is a schema decision somebody else can change. - Be especially careful in a view or a scheduled report. The query was reviewed when the column held no
NULLs, and the firstNULLarrives without raising anything.
NOT IN on a column of your own that holds NULLs is a separate question and behaves differently. A NULL on the left of the operator excludes only that row, the way a NULL normally does. This post is about a NULL in the list, which takes every row with it.
Key points
INtests a value against a list, and a subquery is a list — one that reflects today's data rather than what you typed.NOT INis not the opposite ofINonce aNULLis involved.x NOT IN (a, b, c)meansx <> a AND x <> b AND x <> c.- Comparing anything to
NULLyields unknown, and aWHEREclause keeps only conditions that areTRUE. Unknown is not true. - A value not in the list reaches
TRUE AND UNKNOWN→UNKNOWNand is dropped wrongly. A value in the list reachesFALSE AND UNKNOWN→FALSEand is dropped correctly. Together that is every row, which is why the grid comes back completely empty. - It is not a subquery problem — a hand-typed list containing
NULLcollapses in exactly the same way. - Three fixes: exclude the
NULLs in the subquery, useNOT EXISTS, or use an anti-join. All three return the rowNOT INcould not. NOT EXISTSand the anti-join are immune by construction: an unknown comparison means no match, and there is noANDchain for it to propagate through.- The positive form is safe.
INexpands toOR, andTRUE OR UNKNOWNisTRUE, so aNULLin the list is simply never matched. - The failure mode is correct SQL, no error, no warning and an empty grid. That is indistinguishable from nothing to report, which is why it survives review.
In the next post we will cover EXISTS and NOT EXISTS properly. We used NOT EXISTS here as a fix without explaining how it works. Next time we will look at what the subquery returns, why SELECT 1 and SELECT * make no difference inside one, and why it is immune to the trap we just read about.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode, including the empty results and the truth table. The EMPLOYEES and DEPARTMENTS data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series. Operator behaviour follows the Snowflake IN documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.