16/30
Part 3 of 5 · NULLs and joinsLearn and do

One NULL in the list, and NOT IN is never true

The question: promo codes nobody has used. The queries below use four pieces of syntax:

  • VALUES ('FREESHIP'), ('SPRING'), ('WELCOME') is a table typed into the query, one code per row.
  • promos(code) names that table and its one column.
  • In a NOT EXISTS query, the subquery runs once for each outer row.
  • SELECT 1 is all that subquery needs to return, because only whether a row comes back matters.
WITH promos(code) AS (VALUES ('FREESHIP'), ('SPRING'), ('WELCOME'))
SELECT code
FROM promos
WHERE code NOT IN (SELECT promo FROM orders);

It returns no rows at all. NOT IN is true only when the code differs from every value in the list. Here's that check, written out for WELCOME, the code nobody used:

'WELCOME' NOT IN (SELECT promo FROM orders). The list is NULL, 'FREESHIP', 'SPRING', NULL, NULL:

ComparisonResult
'WELCOME' <> NULLNULL
'WELCOME' <> 'FREESHIP'true
'WELCOME' <> 'SPRING'true
'WELCOME' <> NULLNULL
'WELCOME' <> NULLNULL
all five togetherNULL, so WHERE drops WELCOME

One unknown is enough to make the whole check unknown. NOT EXISTS asks whether a matching row exists, and never compares anything with NULL. Here it finds the customers with no orders, running the subquery once for each customer c:

SELECT c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
name
Dee

In the editor, fix UNUSED_PROMOS with NOT EXISTS.