UNIQUE and NOT NULL: enforce required distinct values
Overview
Use UNIQUE to prevent repeated key values and NOT NULL to require a value. A table can have multiple unique constraints, for example on username and employee number. A unique constraint can span several columns. Run each script separately in a fresh disposable SQLite database with PRAGMA foreign_keys=ON before BEGIN.
First example
CREATE TABLE staff (id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE, badge TEXT UNIQUE);INSERT INTO staff VALUES (1,'mina',NULL),(2,'reza',NULL);SELECT COUNT(*),COUNT(badge) FROM staff;Observed SQLite result (rows in JSON):
[ [ 2, 0 ]]How it works
In SQLite and PostgreSQL 17 by default, UNIQUE permits multiple NULLs. PostgreSQL 17 also offers UNIQUE NULLS NOT DISTINCT to treat NULLs as equal for this constraint. NOT NULL does not reject an empty string. If a business rule prohibits blank names or requires case-insensitive uniqueness, specify and test those rules separately; UNIQUE alone does not establish such policies. A named table constraint such as CONSTRAINT slot_unique UNIQUE(room,day) improves diagnostics and schema maintenance. A unique index can also enforce uniqueness, but index and constraint metadata, eligibility and deferral rules differ by engine.
Practical example
CREATE TABLE slots (room TEXT NOT NULL, day TEXT NOT NULL, UNIQUE(room,day));INSERT INTO slots VALUES ('A','Mon'),('A','Tue'),('B','Mon');SELECT room,COUNT(*) FROM slots GROUP BY room ORDER BY room;Observed SQLite result (rows in JSON):
[ [ "A", 2 ], [ "B", 1 ]]Practice and mistakes
Practice: design a required username and an optional unique badge number. Try duplicate usernames and two missing badge numbers. Explain why a UNIQUE constraint is not the same as a primary key or a non-empty check.
PostgreSQL 17 example — NOT RUN
CREATE TABLE badge (id integer PRIMARY KEY, code text, CONSTRAINT badge_code_uq UNIQUE NULLS NOT DISTINCT (code));INSERT INTO badge VALUES (1,NULL),(2,'X');SELECT id,code FROM badge ORDER BY id;Expected result, not executed: [[1, null], [2, "X"]]