UNIQUE and NOT NULL
NOT NULL requires every row to have a value and UNIQUE forbids repeated values, two independent rules that together match a primary key's guarantee.
Test uniqueness and required values independently, including the database's NULL rules.
A sign-up form has a bug that lets people register twice with the same email. Another form lets customers skip their name entirely. Both bugs live in application code — but two short words in the table definition would have stopped both, no matter which app, script or person wrote the data.
The rule
UNIQUE forbids repeats; NOT NULL forbids blanks. Together they make a column trustworthy.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
phone VARCHAR(15) UNIQUE NOT NULL
);NOT NULL means every row must have a value in that column. Leaving it out of an INSERT (with no default) or setting it to NULL is rejected. It says nothing about repeats — two customers may both be called Asha.
UNIQUE means no two rows may share a value. It says nothing about blanks: in PostgreSQL, MySQL and SQLite, many rows may have NULL in a UNIQUE column, because NULL means "unknown" and two unknowns are not considered equal. SQL Server is the exception: it allows only one NULL in a UNIQUE column.
Combine them and you get "every row has a value, and no value repeats" — the same guarantee as a primary key, which is why phone above could have been the key. The difference: a table has one primary key but may have many UNIQUE columns.
UNIQUE can also cover a combination of columns:
CREATE TABLE product_names (
category VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
UNIQUE (category, name)
);Now "Notebook" can exist in both stationery and gifts, but not twice in stationery.