Constraints in SQL
From the SQL cheat sheet ยท Constraints & Keys ยท verified Jul 2026
Constraints
PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, and DEFAULT.
sql
-- Primary key
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL
);
-- Foreign key
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE
);
-- Add constraint to existing table
ALTER TABLE users ADD CONSTRAINT age_check CHECK (age >= 0);๐ก ON DELETE CASCADE automatically deletes child rows โ use carefully
โก Composite primary keys use multiple columns โ common in junction/pivot tables
๐ RESTRICT is the default ON DELETE behavior โ it prevents deleting referenced rows
๐ข Name your constraints (ADD CONSTRAINT name) โ makes them easier to drop later
constraintsprimary-keyforeign-keyunique