Data Constraints (NOT NULL, UNIQUE, CHECK, DEFAULT)
Protect data quality at the column and table level with declarative constraints.
In plain words
Constraints are rules the database checks every time data is saved, and it refuses anything that breaks them.
Think of it like…
Form validation that the building itself enforces: no matter which entrance someone uses, the door won't open without a valid badge (NOT NULL), each badge number is issued once (UNIQUE), and only adults may enter (CHECK).
Where you’ve seen it
CREATE TABLE products (id bigint PRIMARY KEY, sku text NOT NULL UNIQUE, price numeric(10,2) NOT NULL CHECK (price >= 0), status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'active', 'archived')));: no product can ever have a missing SKU, a negative price or an invalid status.
Words you’ll hear
- NOT NULL
- The column must always have a value.
- UNIQUE
- No two rows may share the value (NULL handling differs by database).
- CHECK
- A boolean condition every row must satisfy.
- DEFAULT
- The value used when an INSERT omits the column.
Visual diagram
Theory & example queries
What each constraint enforces
NOT NULL is the simplest and most valuable: decide for every column whether a missing value is meaningful, and forbid it if not. UNIQUE creates an index and rejects duplicates; it can span several columns (UNIQUE (user_id, date)). CHECK accepts any condition on the row's own columns, such as ranges, allowed values, or end_date >= start_date.
DEFAULT isn't a rule but a fallback: it fills the column when an INSERT leaves it out. If the INSERT explicitly sends NULL, the default isn't used, and the column stays NULL unless it's also NOT NULL. That's why status text NOT NULL DEFAULT 'draft' is the usual pairing.
ALTER TABLE bookingsADD CONSTRAINT bookings_dates_ok CHECK (check_out > check_in);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Representative PostgreSQL status; creation fails and no constraint is added if existing rows violate the date rule.
Key takeaway: NOT NULL by default, UNIQUE for identity, CHECK for business rules, DEFAULT for convenience.
Database differences and adding constraints later
UNIQUE and NULL behave differently across databases. PostgreSQL, MySQL and Oracle allow many NULLs in a UNIQUE column, because NULLs aren't considered equal; PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT to forbid that. SQL Server allows only one NULL. MySQL parsed CHECK constraints but silently ignored them until version 8.0.16.
Adding a constraint to a large existing table checks every row, and existing bad data makes it fail. Clean the data first. In PostgreSQL, ADD CONSTRAINT … CHECK (…) NOT VALID followed by VALIDATE CONSTRAINT avoids a long blocking lock. Give constraints names so violation errors point to the rule that was broken.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
ALTER TABLE ordersADD CONSTRAINT orders_amount_positive CHECK (amount > 0) NOT VALID;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
ALTER TABLE orders VALIDATE CONSTRAINT orders_amount_positive;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: The second command fails if legacy rows with amount <= 0 remain; otherwise it validates the existing data and completes.
then
Key takeaway: Know your database's NULL and CHECK behaviour; validate big tables in two steps.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide what's required
For each column, ask whether a row makes sense without it. If not, make it NOT NULL.
email text NOT NULL
When to use it & trade-offs
What it is
Constraints are rules the database enforces on every write. NOT NULL requires a value, UNIQUE forbids duplicates, CHECK requires a condition to be true (CHECK (price >= 0)), and DEFAULT supplies a value when the column is left out of an INSERT. Together with primary and foreign keys, they keep bad data out no matter which code writes it.
Why it matters: Application validation can be bypassed by a bug, a script, a migration or a second service. Constraints can't. Interviewers ask about them to see whether you push data-quality rules into the database rather than trusting every caller to get them right.
When to reach for it
- NOT NULL on every column that must have a value
- UNIQUE on emails, SKUs and natural keys
- CHECK for ranges, statuses and date order
When to avoid or be careful
- Relying only on application code for data integrity
- Assuming DEFAULT applies when NULL is inserted explicitly
- Unnamed constraints that produce cryptic errors
Constraints vs application validation vs triggers
Strengths: Can't be bypassed; fast; declarative.
Watch out: Error messages need translating into friendly UI messages.
Strengths: Good user experience; can check external things.
Watch out: Skipped by scripts, other services and bugs.
Strengths: Can run arbitrary checks.
Watch out: Hidden logic, slower, harder to debug.
Interview signals & numbers to know
When this topic comes up
- “How do you ensure data quality?”
- Negative prices or invalid statuses in production data
- Duplicate emails
- “What does a CHECK constraint do?”
- Schema design
Benchmarks & rules of thumb
- 4
- column constraints here: NOT NULL, UNIQUE, CHECK, DEFAULT
- MySQL 8.0.16
- CHECK constraints actually enforced
- PostgreSQL 15
- UNIQUE NULLS NOT DISTINCT
Common mistakes & follow-ups
Common interview mistakes
- Leaving columns nullable by default and discovering NULLs nobody expected.
- Inserting NULL explicitly and expecting the DEFAULT to apply.
- Relying on CHECK constraints in MySQL versions before 8.0.16, which ignored them.
Likely interviewer follow-ups
- How does a UNIQUE constraint treat NULL values?
- Why enforce rules in the database if the application already validates input?
- How would you add a NOT NULL constraint to a large existing table safely?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Data Constraints (NOT NULL, UNIQUE, CHECK, DEFAULT) with hands-on SQL practice and interview Q&A.