Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 10/ 160
01. SQL Foundations & Relational Concepts

Data Constraints (NOT NULL, UNIQUE, CHECK, DEFAULT)

Protect data quality at the column and table level with declarative constraints.

BeginnerNOT NULL · UNIQUE / CHECK3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Cross-column CHECKQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE bookings2ADD CONSTRAINT bookings_dates_ok CHECK (check_out > check_in);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/2
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ALTER TABLE

Note: Representative PostgreSQL status; creation fails and no constraint is added if existing rows violate the date rule.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Adding a CHECK without a long lock (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE orders2ADD CONSTRAINT orders_amount_positive CHECK (amount > 0) NOT VALID;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/2
query.sql
1ALTER TABLE orders VALIDATE CONSTRAINT orders_amount_positive;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ALTER TABLE ALTER TABLE

Note: The second command fails if legacy rows with amount <= 0 remain; otherwise it validates the existing data and completes.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then

Key takeaway: Know your database's NULL and CHECK behaviour; validate big tables in two steps.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Decide what's required

For each column, ask whether a row makes sense without it. If not, make it NOT NULL.

Focus at this step

email text NOT NULL

What to watch at this step
Default stance
NOT NULL
Tip: use ← → to move between steps

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

Database constraints
Best for: Rules that must always hold, for every writer

Strengths: Can't be bypassed; fast; declarative.

Watch out: Error messages need translating into friendly UI messages.

Application validation
Best for: Friendly, immediate feedback in forms and APIs

Strengths: Good user experience; can check external things.

Watch out: Skipped by scripts, other services and bugs.

Triggers
Best for: Rules involving other tables that constraints can't express

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?
Interview tip: Make the argument "the database is the last line of defence", then show one table definition using all four. It's concrete and shows design judgement.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Foreign Keys & Referential Integrity (ON DELETE CASCADE, SET NULL)
Next topic
Inserting Records (INSERT INTO, Single vs Multi-Row Inserts)