CodePark/ questions / SQL queries & joins
START PRACTICINGPRACTICE
Backend question · Databases & SQL › SQL queries & joins

Some rows in orders have customer_id set to NULL. What does this query return?

SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
No rows at all

The query returns no rows at all. x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL. Any comparison with NULL gives NULL (unknown), so x <> NULL is NULL. The whole condition can never be true.

It is not "Customers who have no orders", because the NULL in the subquery removes every row. It is also not "An error, because the subquery contains NULL": SQL runs the query without any error, and you just get an empty result.


Fixes:

• Rewrite it with
NOT EXISTS, which does not have this problem.
• Or remove NULLs from the subquery with
WHERE customer_id IS NOT NULL.