Sub topic 3
Defaults and NULLs
This chapter covers what a column receives when an INSERT does not give it a value. It assumes you can write a basic SELECT with WHERE, know the common data types, and have read the previous chapters on the example schema and on INSERT with a column list.
Three ways a column gets its value
When you insert a row, each column ends up with one of three things:
- The value you supplied.
- The column's DEFAULT, if you left the column out of the column list (or used the DEFAULT keyword) and the column has one.
- NULL, if you left the column out and it has no default.
If the result of rule 3 is NULL and the column is declared NOT NULL, the database rejects the statement. The schema from the earlier chapter shows all three cases:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
);| Column | Constraints | If you omit it from the INSERT |
|---|---|---|
| id | PRIMARY KEY | Error in most setups, because a primary key cannot be NULL and there is no default |
| name | NOT NULL | Error, because there is no default to fall back on |
| UNIQUE, nullable | Stored as NULL | |
| status | NOT NULL DEFAULT 'active' | Stored as 'active' |
Some databases generate key values for you (auto-increment, identity, or serial columns). That is a separate feature, and this chapter's schema does not use it, so id must always be supplied.
Defaults in action
The statement below omits email and status:
INSERT INTO customers (id, name)
VALUES (4, 'Edsger Dijkstra');The stored row is (4, 'Edsger Dijkstra', NULL, 'active'). The email column is nullable and has no default, so it becomes NULL. The status column falls back to 'active'.
A default applies only when the column is omitted. If you list the column and supply a value, your value wins, even if it is an empty string:
INSERT INTO customers (id, name, status)
VALUES (5, 'Barbara Liskov', '');This row has status = '', not 'active'. An empty string is a real value. It is not the same as NULL and it does not trigger the default.
Asking for the default explicitly
The standard keyword DEFAULT lets you request the default inside the VALUES list. This is useful when you want to keep every column listed, for example when a program builds the statement.
INSERT INTO customers (id, name, email, status)
VALUES (6, 'Donald Knuth', '[email protected]', DEFAULT);PostgreSQL, MySQL, and SQL Server accept this form. SQLite does not support the DEFAULT keyword in a VALUES list, so with SQLite you omit the column instead.
You can also use DEFAULT in an UPDATE to reset a column to its default:
UPDATE customers
SET status = DEFAULT
WHERE id = 5;Row 5 now has status = 'active'. SQLite does not support this form either.
Defaults are not retroactive
A default is used at the moment of INSERT. Changing a column's default later does not alter rows that already exist. Also, a default is not a constraint: it does not stop someone from supplying a different value.
NULL means "no value"
NULL is a marker for a missing or unknown value. It is not zero, not an empty string, and not the text 'NULL'. Two consequences matter when you change data.
Writing NULL
You can insert NULL explicitly into any column that allows it:
INSERT INTO customers (id, name, email)
VALUES (7, 'Margaret Hamilton', NULL);You can also clear a value with UPDATE:
UPDATE customers
SET email = NULL
WHERE id = 1;Trying the same on a NOT NULL column fails:
UPDATE customers
SET name = NULL
WHERE id = 1;
-- Error: NOT NULL constraint violated. The statement changes no rows.The exact error text differs between databases, but the outcome is the same. The statement is rejected as a whole.
Finding NULLs
NULL is never equal to anything, including another NULL. A comparison with = gives an unknown result, and WHERE keeps only rows where the condition is true. So this matches nothing, even if some emails are NULL:
SELECT id, name FROM customers WHERE email = NULL;Use IS NULL and IS NOT NULL:
SELECT id, name FROM customers WHERE email IS NULL;This matters for safe changes. To fill in missing emails with a placeholder, the condition must use IS NULL:
UPDATE customers
SET email = '[email protected]'
WHERE email IS NULL;Writing WHERE email = NULL would run without error and change zero rows, which is easy to miss. Note also that this update would break the UNIQUE constraint if it touched two rows, because both would receive the same placeholder. Preview with SELECT first, as the later chapter on WHERE safety describes.
NULL and UNIQUE
A UNIQUE constraint treats missing values specially in most databases. PostgreSQL, MySQL, and SQLite allow several rows with NULL in a UNIQUE column, because two unknown values are not considered equal. SQL Server is the notable exception: its UNIQUE constraint allows only one NULL. If you rely on multiple NULLs in a unique column, check your database.
NULL in expressions
Arithmetic or concatenation with NULL usually yields NULL. This affects UPDATE expressions:
UPDATE orders
SET total = total + 5
WHERE id = 100;If total were NULL, the result would stay NULL. In the example schema total is NOT NULL, so this cannot happen there. In a nullable column, use COALESCE, which returns its first non-NULL argument:
UPDATE products
SET stock = COALESCE(stock, 0) + 10
WHERE id = 1;The products table here is only an illustration of a table with a nullable stock column. It is not part of this tutorial's schema.
Defaults and NULLs together
A column can be nullable and have a default. In that case, omitting the column gives the default, while explicitly inserting NULL gives NULL. The default does not replace an explicit NULL.
CREATE TABLE notes (
id INTEGER PRIMARY KEY,
body VARCHAR(200) NOT NULL,
priority VARCHAR(10) DEFAULT 'normal'
);
INSERT INTO notes (id, body) VALUES (1, 'Omitted priority');
INSERT INTO notes (id, body, priority) VALUES (2, 'Explicit NULL', NULL);Row 1 stores 'normal'. Row 2 stores NULL. Oracle behaves differently in some versions, so check its documentation if you use it.
Common mistakes
- Listing a column with NULL and expecting the default. Omit the column or use DEFAULT instead.
- Using
= NULLor<> NULLin WHERE. Use IS NULL and IS NOT NULL. - Using
INSERT INTO customers VALUES (...)with no column list. A later added column or a different column order silently changes what each value means, and the omitted-column defaults no longer help you. - Assuming an empty string and NULL are the same. Most databases treat them as different values. Oracle treats an empty string as NULL, which is a known exception.
Exercises
Exercise
Given the customers table above, what does this statement store in the email and status columns? INSERT INTO customers (id, name) VALUES (8, 'Linus');
Show answer
email is NULL, because the column is nullable and has no default. status is 'active', because the omitted column uses its DEFAULT.
Exercise
A query SELECT * FROM customers WHERE email = NULL; returns no rows, although some customers have no email. Why, and how do you fix it?
Show answer
Comparing anything to NULL with = gives an unknown result, and WHERE keeps only rows where the condition is true. Rewrite the condition as WHERE email IS NULL.
Exercise
What is the difference between INSERT INTO notes (id, body) VALUES (3, 'x'); and INSERT INTO notes (id, body, priority) VALUES (4, 'y', NULL); for the notes table above?
Show answer
The first omits priority, so it receives the default 'normal'. The second supplies NULL explicitly, so priority is stored as NULL and the default is not used.