SQL Constraints
On this page
SQL Constraints
SQL constraints are rules applied to table columns to enforce data integrity and consistency. Constraints help prevent invalid data from being inserted into a table.
Why Constraints Matter
- Prevent missing required values
- Prevent duplicate data
- Ensure relationships between tables
- Enforce valid ranges or formats
Common SQL Constraints
- NOT NULL – ensures a column cannot have a NULL value
- UNIQUE – ensures all values in a column are different
- PRIMARY KEY – uniquely identifies each row
- FOREIGN KEY – links records between tables
- CHECK – ensures values satisfy a condition (support varies)
- DEFAULT – sets a default value when none is provided
Constraints in CREATE TABLE
You can define constraints when creating a table:
CREATE TABLE customers ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(150) UNIQUE, status VARCHAR(20) DEFAULT 'active' );
Constraints in ALTER TABLE
You can also add constraints to an existing table:
ALTER TABLE customers ADD UNIQUE (email);
Foreign Key Example
CREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, order_date DATE NOT NULL, FOREIGN KEY (customer_id) REFERENCES customers(id) );
Common Mistakes
- Not defining a primary key
- Forgetting indexes for foreign key columns (can hurt performance)
- Assuming CHECK works the same in every database system
Next Step
Continue with SQL NOT NULL to learn how to require values in a column.