Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
MySQL Intermediate Free

Constraints & Keys

Lesson 12 of 16 · Database Design 75%

Constraints enforce data integrity.

Constraint Types

  • PRIMARY KEY � unique identifier
  • FOREIGN KEY � references another table
  • NOT NULL � cannot be NULL
  • UNIQUE � no duplicates
  • DEFAULT � default value
  • CHECK � validation rule

Syntax

MYSQL
CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    total DECIMAL(10,2) CHECK (total >= 0),
    status VARCHAR(20) DEFAULT "pending",
    FOREIGN KEY (user_id) REFERENCES users(id)
        ON DELETE CASCADE
);
Table Constraints
SQL
CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    code VARCHAR(20) UNIQUE,
    total DECIMAL(10,2) CHECK (total >= 0),
    status ENUM("pending", "paid", "shipped") DEFAULT "pending",
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
        ON DELETE CASCADE
);

-- Add a UNIQUE constraint
ALTER TABLE users
ADD CONSTRAINT uc_email UNIQUE (email);

-- Add a CHECK constraint (MySQL 8.0.16+)
ALTER TABLE products
ADD CONSTRAINT chk_price CHECK (price > 0);

-- Remove constraint
ALTER TABLE users DROP INDEX uc_email;

Practice

1
Exercise

Create a table with PRIMARY KEY, UNIQUE, and FOREIGN KEY.

Answer
CREATE TABLE reviews (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_id INT NOT NULL,
    rating INT CHECK (rating BETWEEN 1 AND 5),
    FOREIGN KEY (product_id) REFERENCES products(id)
);

Quick Quiz

1

ON DELETE CASCADE does what?

Automatically deletes child rows when parent is deleted.

Choose an answer to continue.

Interview Questions

Both enforce uniqueness. PRIMARY KEY cannot be NULL and only one per table. UNIQUE allows NULLs and multiple per table.

Up next

Subqueries

Lesson 13 of 16 · Advanced Queries