Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are database NULL fields for?

Could anyone explain the usage of NULL in database tables? What is it used for and how is it useful?

like image 888
bodacydo Avatar asked Dec 03 '22 06:12

bodacydo


2 Answers

It is useful to mark "unknown" or missing values.

For instance, if you're storing people, and one of the fields is their birthday, you could allow it to be NULL to signify "We don't know when he was born".

This is in contrast to having non-nullable fields where, for the same type of meaning, you would need to designate a "magic value" which has the same meaning.

For instance, what date should you store in that birthday field to mean "we don't know when he was born"? Should 1970-01-01 be that magic value? What if we suddenly need to store a person that was born on that day?

Now, having said that, NULL is one of the harder issues to handle in database design and engines, since it is a propagating property of a value.

For instance, what is the result of the following:

SELECT *
FROM people
WHERE birthday > #2000-01-01#

SELECT *
FROM people
WHERE NOT (birthday > #2000-01-01#)

(note, the above date syntax might not be legal in any database engine, don't get hung up on it)

If you have lots of people with an "unknown" birthday, ie. NULL, they won't appear in either of the results.

Since in the above two queries, the first one says "all people with criteria X", and the second is "all people without criteria X", you would think that together, the results of those two queries would produce all the people in the database.

However, the queries actually say "all people with a known and definite criteria X."

This is similar to asking someone "am I older than 40?" upon which the other person says "I don't know". If you then proceed to ask "am I younger than 41?", the answer will be the same, he still doesn't know.

Also, any mathematics or comparisons will produce NULL as well.

For instance, what is:

SELECT 10 + NULL AS X

the result is NULL because "10 + unknown" is still unknown.

like image 106
Lasse V. Karlsen Avatar answered Jan 21 '23 09:01

Lasse V. Karlsen


From Wikipedia:

Introduced by the creator of the relational database model, E. F. Codd, SQL Null serves to fulfill the requirement that all true relational database management systems (RDBMS) support a representation of "missing information and inapplicable information"

like image 28
JRL Avatar answered Jan 21 '23 09:01

JRL