Skip to content
wannacode

NULL: no value

Problem

The customer who vanished

Marketing wants to write to every customer outside Sofia. There are 20 customers, 6 of them from Sofia. You expect 14:

SQLdatabase: shop

13 come out. Who is missing? Boris Mitev, who never said which city he is from. He is not from Sofia, yet he is not in the result.

The idea

Unknown

Boris's city is NULL: the absence of a value. It is not empty text and not zero. It means “we do not know”.

That is why SQL works with three answers: true, false and unknown. “Is Boris's city different from Sofia?” We do not know, his city is unknown. The answer is “unknown”, and WHERE keeps only the rows for which it is true.

The same happens when you look for NULL with =:

SQLdatabase: shop

Nothing. NULL = NULL is also “unknown”: two unknown values may be equal, or may not.

The idea

IS NULL

NULL has its own check: IS NULL, and the opposite IS NOT NULL.

SQLdatabase: shop

It is the only correct way. = NULL is a mistake that gives no message, just an empty result.

Try it

No category

Show the name and price of the products that have no category. The field already has an attempt. Run it and fix it.

SQLdatabase: shop

Try it

Everyone outside Sofia

Fix the query from the start of the lesson: every customer outside Sofia, including those without a city.

SQLdatabase: shop

See it

NOT IN and one NULL

A NOT IN list with a NULL in it returns an empty result:

SQLdatabase: shop

Why? city NOT IN ('Sofia', NULL) means city <> 'Sofia' AND city <> NULL. The second part is always “unknown”, so the whole condition is never true.

You will rarely write NULL in a list by hand. But when the list comes from another query and has a NULL in it, you get an empty report with no error at all. We will meet it again with subqueries.

Exercise

The products in a category

Show the name and category of all products that have a category.

SQLdatabase: shop

Test

Check yourself

1. What is NULL?
2. What is the result of NULL = NULL?
3. Which one finds the products without a category?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·