</>
Skip to content
MySQL lessons (34/48)

MySQL — Constraints

What are Constraints?

Constraints enforce rules on table columns to maintain data integrity.

CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE,
    age INT CHECK (age >= 18),
    status VARCHAR(20) DEFAULT 'active'
);

Types of Constraints

ConstraintPurpose
NOT NULLColumn cannot be empty
UNIQUEAll values must be different
PRIMARY KEYUnique identifier, not null
FOREIGN KEYLinks to another table
CHECKValidates a condition
DEFAULTProvides a default value

NOT NULL

ALTER TABLE users MODIFY name VARCHAR(100) NOT NULL;

Adding Constraints After Creation

ALTER TABLE users ADD CONSTRAINT chk_age CHECK (age >= 18);
ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email);
ALTER TABLE users ALTER COLUMN status SET DEFAULT 'active';

Dropping Constraints

ALTER TABLE users DROP CHECK chk_age;
ALTER TABLE users DROP INDEX uq_email;

Naming Constraints

CREATE TABLE orders (
    id INT,
    CONSTRAINT pk_orders PRIMARY KEY (id),
    CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
);

Mini Practice

Write SQL code that:

  1. Creates a table with all constraint types
  2. Adds a CHECK constraint after creation
  3. Adds a UNIQUE constraint to an existing column
  4. Drops a constraint

Up Next

Continue with Primary Key — the unique identifier for each row.

Related Topics

Frequently Asked Questions about Constraints

What is Constraints in MySQL?

Constraints is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Constraints?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Constraints.

Why is Constraints important in MySQL?

Constraints is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.