A constraint is a rule that is applied to a column in a table to ensure that the data in the column meets certain requirements. There are several types of constraints in SQL, including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK.
When students begin designing tables in a database, they often focus only on storing data. But storing data is not enough—what truly matters is keeping the data accurate, meaningful, and consistent.
To achieve this, SQL uses special rules called constraints.
A constraint is simply a rule applied to a table or a column that controls what kind of data can be stored there.
You can think of a constraint as a boundary or guideline that ensures the information inside the database remains clean and reliable.
I often explain it like classroom rules:
The rules don’t stop learning—they help keep everything organized.
Similarly, constraints don’t stop data entry—they help ensure that only correct and valid data is entered.
Why Are Constraints Important?
Constraints help the database:
- Prevent incorrect or invalid data
- Avoid duplicates
- Protect relationships between tables
- Maintain accuracy and consistency
- Reduce errors caused by wrong user input
Without constraints, a database can quickly become messy and unreliable.
Common Types of Constraints
Here are the most important ones you will use:
- PRIMARY KEY Constraint
Ensures each row has a unique, non-null identifier. - FOREIGN KEY Constraint
Links two tables and preserves relationships. - UNIQUE Constraint
Ensures no two rows have the same value in a particular column. - NOT NULL Constraint
Ensures a column cannot be left empty. - CHECK Constraint
Ensures values meet a condition
(e.g., Age must be greater than 18). - DEFAULT Constraint
Assigns a default value if no value is provided.
Simple Example
Suppose you want to make sure that no student has a negative age and every student has a unique roll number.
CREATE TABLE Students (
RollNo INT PRIMARY KEY,
Name VARCHAR(50),
Age INT CHECK (Age > 0),
Email VARCHAR(100) UNIQUE
);
Here:
PRIMARY KEYensures RollNo is uniqueCHECKensures Age is validUNIQUEensures no duplicate emails
Each constraint works like a guard protecting your data.