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
Back to the full SQL cheat sheet