All sample questions / SQL
What does SELECT product FROM filters WHERE category NOT IN ('A', 'B', NULL) return? SQL NULL, CASE and Set Operations
Block 4, NULL, CASE and Set Operations, question 12 of the SQL sample
CREATE TABLE filters (id INTEGER, product TEXT, category TEXT);
INSERT INTO filters VALUES
(1, 'P1', 'A'),
(2, 'P2', 'C'),
(3, 'P3', 'D');
SELECT product FROM filters WHERE category NOT IN ('A', 'B', NULL)
What does this query return?
Show the answer and why each option is right or wrong
Answer, D. (no rows)
- A. P1 P2 P3
- This assumes the NULL in the list is simply ignored, leaving NOT IN to behave as if the list only had A and B, but SQL does not drop NULL members from a list before evaluating it.
- B. P3
- This picks out a single row as if only D somehow escaped the NULL trap, but the NULL in the list affects every row identically, there is no partial escape.
- C. P2 P3
- This is the answer a straightforward reading of NOT IN would suggest, categories C and D are not A or B, but a NULL sitting inside the list turns every row unknown regardless of its own category.
- D. (no rows)
- Correct. Because the list itself contains a NULL, NOT IN can never be confirmed true for any row, so the query returns nothing even though P2 and P3 categories look like an obvious match at first glance.
NOT IN (A, B, NULL) unfolds into value <> A AND value <> B AND value <> NULL, and the last comparison is always unknown. Unknown combined with AND drags the whole expression to unknown or false depending on the other terms, but never to true, so a NULL anywhere inside a NOT IN list quietly empties the result for every row.
The answer above is what SQLite and DuckDB both returned when the snippet was run, not what someone expected it to do.
This question comes from a bank of 502 SQL interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 502 SQL questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free SQL sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.