Sub topic 4
Requiring values with NOT NULL
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you know how CREATE TABLE declares columns and data types. Here you learn what NOT NULL enforces, how it interacts with DEFAULT and other constraints, and which mistakes come up most often.
What NULL means
NULL is a marker meaning "no value." It is not zero, not an empty string, and not the text 'NULL'. A column that allows NULL can hold a value, or it can hold nothing at all. The database does not say why the value is missing. It could be unknown, not applicable, or never entered.
A NOT NULL constraint says that a column must always hold a real value in every row. The database rejects any INSERT or UPDATE that would leave the column as NULL.
By default, columns accept NULL. If you write nothing, you get a nullable column. That default is the reason NOT NULL is worth writing out deliberately.
Declaring NOT NULL
Put NOT NULL after the data type in the column definition.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
phone VARCHAR(30),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Here email, full_name, and created_at are required. phone is left nullable on purpose, because not every customer gives one. The constraint belongs to the column, so it applies to every row and every statement that touches the column.
You may also write NULL explicitly to mark a column as nullable. Most people omit it, but it can make intent clear in a long definition. SQL Server and MySQL accept it, and so does PostgreSQL.
What the database rejects
Two kinds of statements can violate NOT NULL.
- An
INSERTthat suppliesNULLexplicitly, or omits the column when no default exists. - An
UPDATEthat sets the column toNULL.
-- Explicit NULL: rejected
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', NULL);
-- Column omitted and no default exists: rejected
INSERT INTO customers (email)
VALUES ('[email protected]');
-- Setting an existing value to NULL: rejected
UPDATE customers
SET full_name = NULL
WHERE customer_id = 1;PostgreSQL reports an error like this one:
ERROR: null value in column "full_name" of relation "customers" violates not-null constraintThe message names the column and the table, which makes NOT NULL errors easy to trace. A rejected statement changes nothing. In a multi-row INSERT, a single bad row causes the whole statement to fail.
Omitting a column is not the same everywhere
When you leave a column out of an INSERT, the database fills it with its default. If the column has no DEFAULT, the value is NULL, and NOT NULL then rejects the row.
MySQL deserves a warning here. In non-strict SQL modes, MySQL may quietly insert an implicit default such as '' or 0 for an omitted NOT NULL column and issue only a warning. Modern MySQL versions enable strict mode by default, which raises an error instead. If you inherit an older server, check sql_mode.
NOT NULL and DEFAULT together
NOT NULL and DEFAULT solve different problems. NOT NULL forbids missing values. DEFAULT supplies a value when the statement does not.
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL
);
INSERT INTO orders (customer_id, total_amount)
VALUES (1, 25.00);The insert omits status, so the default 'new' is used and the row is valid. The insert does not omit total_amount, and it has no default, so leaving it out would fail.
A default does not stop someone from writing NULL explicitly. This surprises many people:
INSERT INTO orders (customer_id, status, total_amount)
VALUES (1, NULL, 25.00);The statement fails, because status is NOT NULL. If status were nullable with DEFAULT 'new', the explicit NULL would be stored as NULL. The default applies only when the column is omitted or when you write the keyword DEFAULT. The pair NOT NULL DEFAULT ... is the usual way to guarantee that a column always has a meaningful value.
NOT NULL is not a CHECK against empty text
NOT NULL rejects NULL only. It does not reject an empty string.
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', '');On PostgreSQL, SQL Server, and MySQL, this succeeds. '' is a real value of length zero. If you want to forbid blank names, add a CHECK, which a later chapter covers:
ALTER TABLE customers
ADD CONSTRAINT ck_customers_name_not_blank CHECK (full_name <> '');Oracle behaves differently. It treats an empty string as NULL, so NOT NULL does reject '' there. Keep this in mind when moving schemas between systems.
How NOT NULL interacts with other constraints
- PRIMARY KEY implies
NOT NULLon every column of the key. WritingNOT NULLagain is harmless and some teams do it for clarity. In SQL Server, a primary key column must be non-null, and the database enforces that for you. - UNIQUE does not imply
NOT NULL. BecauseNULLmeans "unknown," most systems let a unique column hold severalNULLrows. SQL Server is the exception and allows only one. This is whyemail VARCHAR(255) NOT NULL UNIQUEis a common pairing. - FOREIGN KEY columns accept
NULLunless you forbid it. ANULLforeign key means "no related row," and the database does not check it against the parent table. Markingcustomer_idasNOT NULLturns the relationship into a mandatory one. Leaving it nullable makes it optional. - CHECK passes when its condition evaluates to unknown. A check such as
CHECK (total_amount >= 0)accepts aNULLamount, because comparingNULLto anything gives unknown, not false. AddNOT NULLalongside theCHECKwhen a value must be both present and valid.
The last point is the one that causes real bugs. Each constraint covers a separate rule, and you usually need both.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) CHECK (price >= 0)
);
-- Succeeds, because the CHECK evaluates to unknown for NULL
INSERT INTO products (name, price) VALUES ('Mystery box', NULL);Changing price to NUMERIC(10, 2) NOT NULL CHECK (price >= 0) closes the gap.
Choosing which columns to make NOT NULL
Start from the opposite assumption: make a column NOT NULL unless you can name a case where the value is legitimately absent. Several reasons support this.
- Queries get simpler. You do not need
IS NULLchecks orCOALESCEcalls for columns that always have values. NULLcomparisons behave unexpectedly.WHERE status <> 'paid'skips rows wherestatusisNULL, because the comparison yields unknown.- Aggregates such as
AVGandCOUNT(column)ignoreNULL, which can quietly skew results. - Applications can trust the data without defensive code.
Keep a column nullable when absence carries meaning, such as shipped_at on an order that has not shipped yet. Avoid inventing placeholder values like 'N/A' or 0 or 1900-01-01 to dodge NULL. Placeholders look like real data and corrupt reports. A nullable column is more honest.
Adding NOT NULL to an existing table
You can change a column's nullability later with ALTER TABLE. The syntax differs by system.
-- PostgreSQL
ALTER TABLE customers ALTER COLUMN phone SET NOT NULL;
ALTER TABLE customers ALTER COLUMN phone DROP NOT NULL;
-- SQL Server (the type must be restated)
ALTER TABLE customers ALTER COLUMN phone VARCHAR(30) NOT NULL;
-- MySQL (the full column definition must be restated)
ALTER TABLE customers MODIFY phone VARCHAR(30) NOT NULL;Adding NOT NULL fails if any existing row already holds NULL in that column. Find the offenders first, fix them, then apply the constraint:
SELECT customer_id FROM customers WHERE phone IS NULL;
UPDATE customers SET phone = 'unknown' WHERE phone IS NULL;Adding a NOT NULL column to a table that already has rows requires a default, or the new column would be NULL in existing rows:
ALTER TABLE customers
ADD COLUMN loyalty_tier VARCHAR(20) NOT NULL DEFAULT 'standard';On very large tables, rewriting every row can take time and hold locks. Modern PostgreSQL versions add a constant default without rewriting the table, but older versions and other systems may not. Test on a copy first.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Insert fails with "null value violates not-null constraint" | A required column was omitted and has no default | Supply the value or add a `DEFAULT` |
| `ALTER ... SET NOT NULL` fails | Existing rows hold `NULL` | Update those rows first |
| Blank names still get stored | `NOT NULL` does not reject `''` | Add a `CHECK (col <> '')` |
| Negative or missing prices slip through | `CHECK` passes on `NULL` | Add `NOT NULL` |
| Explicit `NULL` ignores the default | Defaults apply only to omitted columns | Make the column `NOT NULL`, or use the `DEFAULT` keyword |
Exercise
A table is defined with price NUMERIC(10, 2) DEFAULT 0 CHECK (price >= 0). What happens when you run INSERT INTO products (name, price) VALUES ('Pen', NULL);, and what single change makes the database reject that statement?
Show answer
The statement succeeds and stores NULL. The default applies only when the column is omitted, and the CHECK evaluates to unknown for NULL, which counts as a pass. Adding NOT NULL to the price column makes the database reject the statement.
Exercise
You need to add NOT NULL to customers.phone, but 40 rows have NULL in that column. List the steps in a safe order.
Show answer
First find the rows with SELECT ... WHERE phone IS NULL. Next decide on a replacement value and run an UPDATE to fill the gaps. Then run the ALTER TABLE that sets NOT NULL for your database system. If a replacement value is not honest, keep the column nullable instead.