FOREIGN KEY — Ensures relationships between tables stay valid
CHECK — Validates that values meet a specific condition
Constraints are your last line of defense — they catch bad data that application code lets through.
Why Constraints Matter
Without Constraints
With Constraints
Duplicate emails in users table
UNIQUE index rejects duplicates
Orders reference nonexistent customers
FOREIGN KEY prevents orphaned rows
Negative salaries inserted
CHECK constraint validates ranges
Required fields left blank
NOT NULL prevents missing values
Application bug inserts garbage
Database rejects invalid data
NOT NULL
-- Column-level NOT NULL constraint
CREATE TABLE employees (
employee_id INTEGER NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
phone VARCHAR(20) -- NULL allowed (optional)
);
-- Attempting to insert NULL into a NOT NULL column fails
INSERT INTO employees (employee_id, first_name, last_name, email, phone)
VALUES (1, 'John', NULL, 'john@example.com', '555-0100');
-- ERROR: null value in column "last_name" violates NOT-null constraint
UNIQUE
-- Single-column UNIQUE constraint
CREATE TABLE users (
user_id INTEGER NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
username VARCHAR(50) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Multi-column UNIQUE constraint (composite)
CREATE TABLE course_enrollments (
enrollment_id INTEGER NOT NULL,
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
UNIQUE (student_id, course_id) -- A student can't enroll in the same course twice
);
-- Drop a constraint
ALTER TABLE employees
DROP CONSTRAINT chk_salary_positive;
Constraint Summary Table
Constraint
Purpose
NULL Allowed?
Multiple Per Table?
NOT NULL
Prevents NULL values
N/A (enforces non-NULL)
✅ (all columns)
UNIQUE
Ensures all values are different
Yes (one NULL)
✅
PRIMARY KEY
Uniquely identifies each row
❌ No
❌ One only
FOREIGN KEY
Ensures valid references
Yes
✅
CHECK
Validates a condition
Yes (NULL passes)
✅
DEFAULT
Provides a fallback value
N/A (used on INSERT)
✅
Best Practices
Practice
Why
Always define a PRIMARY KEY
Every table needs a reliable row identifier
Add NOT NULL to required fields
Prevent incomplete data at the source
Use CHECK constraints for business rules
Enforce ranges, enums, and logic in the database
Name your constraints
Makes error messages readable and debugging easier
Use FOREIGN KEY with ON DELETE behavior
Prevent orphaned rows and undefined behavior
Index foreign key columns
Improves JOIN performance and referential checks
Don't rely solely on application validation
Application code can be bypassed — constraints are the safety net
CW
ChatWhole Learn Editorial Team
Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.