Sub topic 13
Constraints: NOT NULL, UNIQUE, and CHECK
This chapter assumes you know basic SELECT, WHERE, and JOIN syntax, and that you have read the earlier chapters on three-valued logic and on how WHERE treats UNKNOWN. A constraint is a rule the database enforces on every INSERT and UPDATE. Constraints interact with NULL in ways that surprise people, because the rule for rejecting a row is not the mirror image of the rule WHERE uses to keep a row.
Two Opposite Rules for UNKNOWN
A condition in a query and a condition in a constraint both evaluate to TRUE, FALSE, or UNKNOWN. The two contexts treat UNKNOWN differently:
| Context | Row is kept or accepted when the condition is | UNKNOWN means |
|---|---|---|
| WHERE | TRUE | Row is filtered out |
| CHECK constraint | TRUE or UNKNOWN | Row is accepted |
| NOT NULL | The value is not NULL | Row is rejected if NULL |
| UNIQUE | No other row has an equal, non-NULL key | NULLs are not equal to anything |
A CHECK constraint rejects a row only when its condition is FALSE. WHERE rejects a row unless its condition is TRUE. This difference is the source of most constraint surprises with NULL.
NOT NULL
NOT NULL is the simplest constraint. It forbids NULL in a column, so any INSERT or UPDATE that would store NULL fails with an error.
CREATE TABLE staff (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INTEGER,
commission NUMERIC(8,2)
);
INSERT INTO staff (id, name) VALUES (1, 'Ada'); -- succeeds
INSERT INTO staff (id, name) VALUES (2, NULL); -- fails: name is NOT NULL
INSERT INTO staff (id) VALUES (3); -- fails: no default, so name would be NULLThe third statement fails because a column you omit receives its default value, and the default is NULL unless you declare another one. A column that is NOT NULL and has no DEFAULT must therefore be supplied on every insert.
Primary key columns are implicitly NOT NULL in standard SQL. A few systems have historically allowed exceptions (for example, SQLite permits NULL in non-integer primary key columns unless you add NOT NULL), so declare it explicitly if portability matters.
Adding NOT NULL to an existing column
You cannot add NOT NULL while NULLs are present. The usual sequence is to fill in the gaps first, then add the constraint:
UPDATE staff SET commission = 0 WHERE commission IS NULL;
-- PostgreSQL syntax; other systems use MODIFY or ALTER COLUMN ... NOT NULL variants.
ALTER TABLE staff ALTER COLUMN commission SET NOT NULL;Before you do this, ask whether 0 is a true value. A zero commission means "earns nothing", while NULL meant "not recorded". Filling in zeros changes the meaning of the data and changes what AVG returns, as the aggregates chapter showed.
UNIQUE and NULL
A UNIQUE constraint requires that no two rows have the same value in the constrained columns. Because NULL = NULL is UNKNOWN rather than TRUE, standard SQL treats two NULLs as not duplicates. A UNIQUE column can therefore hold many NULLs.
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
INSERT INTO accounts (id, email) VALUES (1, '[email protected]'); -- succeeds
INSERT INTO accounts (id, email) VALUES (2, NULL); -- succeeds
INSERT INTO accounts (id, email) VALUES (3, NULL); -- succeeds in most systems
INSERT INTO accounts (id, email) VALUES (4, '[email protected]'); -- fails: duplicateThis is often what you want. An optional email address should be unique when present, and rows with no email should not collide with each other.
Multi-column UNIQUE
With a composite key, a duplicate requires every column to be equal and non-NULL. If any column in the key is NULL, the row is generally accepted, even when the other columns match an existing row.
CREATE TABLE bookings (
room_id INTEGER,
slot INTEGER,
UNIQUE (room_id, slot)
);
INSERT INTO bookings VALUES (10, NULL);
INSERT INTO bookings VALUES (10, NULL); -- accepted by most systems, although room_id matchesVendor differences
The "NULLs are distinct" behavior is the SQL standard default, but not every system follows it.
- PostgreSQL, MySQL, SQLite, and Oracle allow multiple NULLs in a single-column UNIQUE constraint. Oracle treats a composite key with all columns NULL as not a duplicate, but two rows with the same non-NULL values in some columns and NULL in others are treated as duplicates.
- SQL Server treats NULLs as equal in a UNIQUE constraint, so it permits only one NULL.
- PostgreSQL 15 and later accept
UNIQUE NULLS NOT DISTINCT, which makes NULLs count as equal and so allows only one.
-- PostgreSQL 15+: at most one row can have a NULL email.
CREATE TABLE accounts_strict (
id INTEGER PRIMARY KEY,
email VARCHAR(100) UNIQUE NULLS NOT DISTINCT
);On systems without that option, a common workaround for "at most one NULL" is a unique index on an expression, such as COALESCE(email, ''). Another is a filtered unique index. SQL Server's behavior is the reverse case: to allow many NULLs there, create a filtered unique index with WHERE email IS NOT NULL.
CHECK and NULL
A CHECK constraint holds a boolean expression. The row is rejected only if the expression is FALSE. If the expression evaluates to UNKNOWN because a NULL is involved, the row passes.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
price NUMERIC(8,2),
CHECK (price > 0)
);
INSERT INTO products VALUES (1, 5.00); -- TRUE, accepted
INSERT INTO products VALUES (2, -1.00); -- FALSE, rejected
INSERT INTO products VALUES (3, NULL); -- UNKNOWN, acceptedThe third insert succeeds, which surprises people who read CHECK (price > 0) as "price must be positive". The accurate reading is "price must not be zero or negative if it has a value". To require a value, combine CHECK with NOT NULL:
CREATE TABLE products_strict (
id INTEGER PRIMARY KEY,
price NUMERIC(8,2) NOT NULL CHECK (price > 0)
);Writing CHECKs that involve several columns
NULL in any column of a multi-column CHECK can turn the whole expression UNKNOWN and let a bad row through. Suppose a sale must have an end date after its start date:
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
starts_on DATE,
ends_on DATE,
CHECK (ends_on > starts_on)
);
INSERT INTO sales VALUES (1, DATE '2026-12-01', DATE '2026-11-01'); -- rejected
INSERT INTO sales VALUES (2, DATE '2026-12-01', NULL); -- acceptedIf an open-ended sale (no end date) is legitimate, the second insert is correct. If you want "both dates or neither", state it explicitly:
CREATE TABLE sales_paired (
id INTEGER PRIMARY KEY,
starts_on DATE,
ends_on DATE,
CHECK ((starts_on IS NULL) = (ends_on IS NULL)),
CHECK (ends_on > starts_on)
);The first CHECK compares two boolean results from IS NULL. IS NULL never returns UNKNOWN, so this expression is always TRUE or FALSE. The second CHECK still passes when either date is NULL, but the first one already guarantees the dates are both present or both absent.
Requiring exactly one of several columns
A pattern that depends on this behavior is "exactly one of these columns must be filled in". Write it with IS NULL tests so UNKNOWN cannot occur:
CREATE TABLE contacts (
id INTEGER PRIMARY KEY,
email VARCHAR(100),
phone VARCHAR(30),
CHECK ((email IS NOT NULL AND phone IS NULL)
OR (email IS NULL AND phone IS NOT NULL))
);Some systems provide a helper such as PostgreSQL's num_nonnulls(email, phone) = 1, but the portable form above works everywhere.
Common Mistakes
- Assuming
CHECK (col > 0)rejects NULL. It does not. Add NOT NULL. - Assuming UNIQUE allows only one NULL. Most systems allow many, and SQL Server allows one.
- Adding NOT NULL to a populated column without first handling existing NULLs, which makes the ALTER fail.
- Replacing NULLs with a sentinel such as 0 or an empty string just to satisfy NOT NULL, which makes "unknown" look like a real value.
- Relying on the default NULL placement in a composite UNIQUE key without testing it on your target database.
Testing Your Constraints
Test constraints with rows on both sides of the rule, including NULLs. For each constraint, try one row that should pass, one that should fail, and one with NULL in every nullable column the constraint touches. Run these as separate statements, because a failed INSERT in a multi-row statement rolls back the whole statement.
-- Expect the first to succeed and the second to fail.
INSERT INTO products_strict VALUES (1, 9.99);
INSERT INTO products_strict VALUES (2, NULL);Exercise
A table is defined as CREATE TABLE items (id INTEGER PRIMARY KEY, qty INTEGER, CHECK (qty >= 0)). Which of these inserts succeed in standard SQL: (1, 5), (2, -3), (3, NULL)? Then change the definition so that (3, NULL) is also rejected.
Show answer
(1, 5) succeeds because 5 >= 0 is TRUE. (2, -3) fails because -3 >= 0 is FALSE. (3, NULL) succeeds because NULL >= 0 is UNKNOWN, and a CHECK rejects a row only when the condition is FALSE. To reject it, declare the column as qty INTEGER NOT NULL, keeping the CHECK.
Exercise
A table has email VARCHAR(100) UNIQUE. You insert three rows with email set to NULL. In PostgreSQL 14, how many succeed, and what would you change in PostgreSQL 15 to allow at most one NULL?
Show answer
All three succeed, because NULL = NULL is UNKNOWN and so the NULLs are not considered duplicates. In PostgreSQL 15 or later, declare the column as email VARCHAR(100) UNIQUE NULLS NOT DISTINCT, which treats NULLs as equal and allows only one.
Exercise
Write a CHECK constraint for a table with columns discount_pct and coupon_code so that a coupon code is required whenever a discount is present, and a discount is required whenever a coupon code is present. Both may be NULL together.
Show answer
CHECK ((discount_pct IS NULL) = (coupon_code IS NULL)). IS NULL always returns TRUE or FALSE, so the comparison is never UNKNOWN, and a row with only one of the two columns filled in evaluates to FALSE and is rejected.