Sub topic 3
Defaults and NULLs in SQL
Assume you know basic SELECT queries, tables, columns, data types, and primary and foreign keys. This chapter focuses on two ways an INSERT can represent missing information: a column default and the special value NULL.
A default fills an omitted column
A default is a value the database supplies when an INSERT does not provide a value for that column. Defaults are defined in the table schema.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255),
status VARCHAR(20) NOT NULL DEFAULT 'active'
);Here, status has a default of 'active'. The following statement omits status, so the database supplies that value:
INSERT INTO customers (id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
SELECT id, name, email, status
FROM customers;The new row has status = 'active'.
Always list the columns you are providing. This makes the statement clear and prevents it from breaking when someone adds a column to the table.
NULL means no known value
NULL is a special marker meaning that a value is absent, unknown, or not applicable. It is different from:
0, which is a number.'', which is an empty text value.'NULL', which is ordinary text containing four letters.
The email column above allows NULL because it has no NOT NULL constraint:
INSERT INTO customers (id, name, email)
VALUES
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', NULL);The third row has no known email address. You can test for NULL with IS NULL or IS NOT NULL. Do not use email = NULL; comparisons with NULL produce an unknown result.
SELECT id, name
FROM customers
WHERE email IS NULL;Defaults do not override explicit NULL
An omitted column and an explicit NULL are different inputs:
INSERT INTO customers (id, name)
VALUES (4, 'Katherine Johnson');
-- status becomes 'active'
INSERT INTO customers (id, name, status)
VALUES (5, 'Dorothy Vaughan', NULL);
-- fails because status is NOT NULLThe second statement fails. The DEFAULT value does not replace an explicit NULL, and the NOT NULL constraint rejects it. You can request a default explicitly with the DEFAULT keyword:
INSERT INTO customers (id, name, status)
VALUES (6, 'Mary Jackson', DEFAULT);To replace missing values while reading data, use COALESCE. It returns the first non-NULL expression:
SELECT name, COALESCE(email, 'no email provided') AS email
FROM customers;This changes only the query result. It does not change stored data.
Exercise
What happens when an INSERT omits a column with DEFAULT 'new', and what happens when it explicitly supplies NULL for that column?
Show answer
The omitted column receives 'new'. An explicit NULL remains NULL if the column allows it; otherwise a NOT NULL constraint rejects the statement.