Learn SQL
-- constraints.unique_check_default

UNIQUE, CHECK & DEFAULT in SQL

Column-level rules: no duplicates, no nonsense, no blanks

--concept

Beyond keys, tables carry column rules. UNIQUE forbids repeated values (usernames, emails). CHECK enforces a boolean condition on every write (salary >= 0). DEFAULT supplies a value when INSERT leaves the column out. Together they push data validation into the database — the one place every writer must pass through.

--how it works
1

UNIQUE guards sets of values

email VARCHAR(80) UNIQUE — the engine maintains a hidden unique index and rejects the second occurrence of any value at write time.

2

CHECK guards conditions

salary DECIMAL(10,2) CHECK (salary >= 0) — evaluated on every INSERT and UPDATE; a false row is rejected with the constraint’s name in the error.

3

DEFAULT fills the gaps

bonus DECIMAL(10,2) DEFAULT 0 — omit the column in INSERT and the engine writes 0, not NULL. The written value is real, so later reads and aggregates see it.

4

Rules compose per column

One column can carry NOT NULL, UNIQUE and a CHECK together; table-level CHECKs can compare two columns (end_date > start_date).

5

Validation is total

Constraints apply to every writer — the app, the migration script, the analyst’s bulk load. The database is the one gate everyone must pass.

--visualization
staffemailUNIQUEno second a@x.comsalaryCHECK (salary >= 0)no nonsense valuesbonusDEFAULT 0auto-filled when omittedidPRIMARY KEYunique identityvalidation lives in the database — every writer passes throughINSERT INTO staff (id, email, salary)VALUES (1, 'a@x.com', -5);CHECK: -5 >= 0 → ?evaluated on every INSERT and UPDATE… rules checkingUNIQUE → CHECK → DEFAULT
Stage 1 / 4
The lesson's staff table: email UNIQUE, salary CHECK (salary >= 0), bonus DEFAULT 0 — rules live in the engine.
--example
query.sql
1CREATE TABLE staff (
2 id INTEGER PRIMARY KEY,
3 email VARCHAR(80) UNIQUE,
4 salary DECIMAL(10,2) CHECK (salary >= 0),
5 bonus DECIMAL(10,2) DEFAULT 0
6);
7INSERT INTO staff (id, email, salary) VALUES (1, 'a@x.com', -5);
Result
error
ERROR: new row for relation "staff" violates check constraint "staff_salary_check"

The CHECK rejects the negative salary regardless of which app, script or intern sent it. The same table would also refuse a second a@x.com (UNIQUE) and fill bonus with 0 whenever it is omitted (DEFAULT).

--variants

CHECK rejects bad data

A negative salary violates the declared rule — regardless of who sent it.

query.sql
1CREATE TABLE staff (
2 id INTEGER PRIMARY KEY,
3 email VARCHAR(80) UNIQUE,
4 salary DECIMAL(10,2) CHECK (salary >= 0),
5 bonus DECIMAL(10,2) DEFAULT 0
6);
7INSERT INTO staff (id, email, salary) VALUES (1, 'a@x.com', -5);
Result
error
ERROR: new row for relation "staff" violates check constraint "staff_salary_check"
1The engine evaluates salary >= 0 against the proposed row: −5 fails.
2The insert aborts with the constraint name — staff_salary_check — in the message.
3No application code was involved; the data model itself refused the lie.

UNIQUE rejects the second value

Two accounts cannot share one email.

query.sql
1INSERT INTO staff (id, email, salary) VALUES (2, 'a@x.com', 60000);
2-- row (1, 'a@x.com', …) already exists
Result
error
ERROR: duplicate key value violates unique constraint "staff_email_key"
1The hidden unique index on email already contains a@x.com.
2The second insert is rejected like a primary-key clash — same mechanism, different column.
3Note: multiple NULLs are allowed in a UNIQUE column — “unknown” is never a duplicate.

DEFAULT supplies the omitted value

bonus was not mentioned, but the row gets 0 — not NULL.

query.sql
1INSERT INTO staff (id, email, salary) VALUES (3, 'b@x.com', 61000);
2SELECT id, email, salary, bonus FROM staff WHERE id = 3;
Result
idemailsalarybonus
3b@x.com610000
1The column list omits bonus, so DEFAULT 0 applies.
2The stored value is a real 0 — SUM(bonus) and comparisons treat it as a number.
3DEFAULT NULL is the implicit choice when you declare nothing at all.

Table-level CHECK spans columns

A booking cannot end before it starts.

query.sql
1CREATE TABLE bookings (
2 id INTEGER PRIMARY KEY,
3 start_at DATE NOT NULL,
4 end_at DATE NOT NULL,
5 CHECK (end_at > start_at)
6);
7INSERT INTO bookings VALUES (1, '2026-05-10', '2026-05-08');
Result
error
ERROR: new row for relation "bookings" violates check constraint "bookings_check"
1The rule compares two columns of the same row — impossible to express as a per-column CHECK.
2The row is rejected at the door; no later cleanup query can ever find an inverted booking.
3Time-travel-proof: yesterday’s valid data stays valid no matter what code runs tomorrow.
--key facts
Unique ≠ primarya table has one PRIMARY KEY but any number of UNIQUE constraints
CHECK can compare columnsCHECK (end_date > start_date) spans two columns of the same row
Migrations matteradding a CHECK to a populated table validates old rows too — plan for failures
--use cases
Emails, usernames, domain slugs — anything that identifies by value (UNIQUE)
Physical sanity: quantity > 0, percentage between 0 and 100, dates in order (CHECK)
Operational defaults: status = 'active', counter = 0, created_at = NOW() (DEFAULT)
Defence in depth: app validation for UX, database constraints for truth
--under the hood
UNIQUE and PRIMARY KEY constraints are enforced by unique indexes — the cost is identical to a hand-built index.
Bulk loads are fastest with constraints deferred or dropped, then re-added and validated in one sweep — PostgreSQL supports NOT VALID for exactly this.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.