Exploring MySQL Constraints: NOT NULL – With examples.

Many times, we nonchalantly slap the NOT NULL constraint on our database columns during table creation. But what is NOT NULL? And more importantly, what is it used for? We are going to learn together. This blog post is part of a series in which I explore and cover MySQL constraints.


overview-of-circle-with-line-through-tennis-court

Photo by Ben Hershey on Unsplash

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.
OS and DB used:

  • Xubuntu Linux 16.04.5 LTS (Xenial Xerus)
  • MySQL 5.7.23

Be sure and visit other accompanying blog posts I’ve written on MySQL Constraints:

NOT NULL is one of the (few) available constraints in MySQL. It is defined at the column level and prevents those columns from storing the NULL value.

What is a Constraint?

A constraint can be thought of as a requirement or restriction you enforce on a database table column to ensure data integrity. Data must then meet the specification prior to being stored. Oftentimes, these constraints are associated with any business rules you may have.

To understand how NOT NULL helps us, we need to understand what NULL is. Also, what it is not. Both of which will be explored as we progress in this blog post.

Starting off, we have this table containing INTEGER, VARCHAR, NUMERIC, and CHAR data types, specifying all of them with the NOT NULL constraint:

1
2
3
4
5
6
mysql> CREATE TABLE various(
    -> i_id INTEGER NOT NULL,
    -> t_word VARCHAR(20) NOT NULL,
    -> n_num NUMERIC(4,2) NOT NULL,
    -> c_char CHAR(5) NOT NULL);
Query OK, 0 rows affected (0.33 sec)

I’ll INSERT a row of generic sample data values to build off from:

1
2
3
4
5
6
7
8
9
10
11
mysql> INSERT INTO various(i_id, t_word, n_num, c_char)
    -> VALUES (10, 'Campfire', 33.20, 'COORD');
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM various;
+------+----------+-------+--------+
| i_id | t_word   | n_num | c_char |
+------+----------+-------+--------+
|   10 | Campfire | 33.20 | COORD  |
+------+----------+-------+--------+
1 row in set (0.00 sec)

Then INSERT NULL values on each column:

1
2
3
4
5
6
7
8
9
10
11
12
mysql> INSERT INTO various(i_id, t_word, n_num, c_char)
    -> VALUES (NULL, NULL, NULL, NULL);
ERROR 1048 (23000): Column 'i_id' cannot be null
mysql> INSERT INTO various(i_id, t_word, n_num, c_char)
    -> VALUES (99, NULL, NULL, NULL);
ERROR 1048 (23000): Column 't_word' cannot be null
mysql> INSERT INTO various(i_id, t_word, n_num, c_char)
    -> VALUES (99, 'Happy', NULL, NULL);
ERROR 1048 (23000): Column 'n_num' cannot be null
mysql> INSERT INTO various(i_id, t_word, n_num, c_char)
    -> VALUES (99, 'Happy', 12.33, NULL);
ERROR 1048 (23000): Column 'c_char' cannot be null

From this example, we can deduce that the INSERT‘s failed because NULL values were provided for those columns defined with the NOT NULL constraint.

Common Misconception(s)

“So NULL is the same thing as 0 (zero) or the empty string ‘ ‘ right?”
This line of thinking is prevalent with many new SQL developers just starting out. It took me a while to solidify the concept personally.
We can better understand, with an example, showing this misconception is simply false.

I’ll run an INSERT having both the empty string and a 0 value for the current table columns.

1
2
3
mysql> INSERT INTO various(i_id, t_word, n_num, c_char)
    -> VALUES (0, '', 0, '');
Query OK, 1 row affected (0.18 sec)

What?!?
That INSERT was successful?
So, what values are present in the table then?

1
2
3
4
5
6
7
8
mysql> SELECT * FROM various;
+------+----------+-------+--------+
| i_id | t_word   | n_num | c_char |
+------+----------+-------+--------+
|   10 | Campfire | 33.20 | COORD  |
|    0 |          |  0.00 |        |
+------+----------+-------+--------+
2 rows in set (0.00 sec)

“So the empty string is the same thing as NULL.”
Let’s ‘debunk’ this misconception by adding in another column that will accept NULL. Simply adding in the column will clearly show us that this is in fact, a misconception.

1
2
3
mysql> ALTER TABLE various ADD COLUMN name TEXT AFTER c_char;
Query OK, 0 rows affected (0.49 sec)
Records: 0  Duplicates: 0  Warnings: 0

See with this SELECT query:

1
2
3
4
5
6
7
8
mysql> SELECT * FROM various;
+------+----------+-------+--------+------+
| i_id | t_word   | n_num | c_char | name |
+------+----------+-------+--------+------+
|   10 | Campfire | 33.20 | COORD  | NULL |
|    0 |          |  0.00 |        | NULL |
+------+----------+-------+--------+------+
2 rows in set (0.00 sec)

This example proves that NULL is not the same thing as 0 (zero) or the empty string ‘ ‘.
Then what is NULL?

NULL is unknown. NULL is not equivalent to anything. Not even another NULL value.
The incredible, masterfully explained blog post The Three-Valued Logic of SQL (which you should definitely read – no questions asked), explains this brilliantly, relating that NULL can be thought of as random or,

“could be anything”

(quoted directly from linked article).

Therefore tests for equality or comparison with NULL are tricky at best.

Not to veer too deep into a rabbit-hole, I will mention that in SQL (MySQL included) we have the IS NULL operator and its converse, IS NOT NULL for tests with NULL.

Points to remember…
  • By default, during table creation, all columns have the NULL specification unless otherwise defined. Meaning, NULL can be stored for that column.
  • NOT NULL is a column level constraint and is not defined at the table level.
  • NULL is not the same thing as zero (0) or the empty string ‘ ‘.
Additional Supporting Reading Resources

As I mentioned at the top of the post, I am blogging about Constraints in the MySQL ecosystem so be sure and look for other similar blog posts forthcoming soon.

Like what you have read? See anything incorrect? Please share your thoughts and comments below. Thanks for reading!!!

Explore the official MySQL 5.7 Online Manual for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Advertisements

One thought on “Exploring MySQL Constraints: NOT NULL – With examples.

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.