Database constraints are rules applied to database tables to make sure the data stored is accurate, consistent, and reliable.
Think of them as guardrails for your data — they prevent invalid or unwanted data from getting into the database.
Why database constraints are needed
They help to:
- Prevent duplicate or invalid data
- Maintain data integrity
- Enforce relationships between tables
- Reduce bugs caused by bad data
Common types of database constraints
1. PRIMARY KEY
- Uniquely identifies each row in a table
- Cannot be
NULL - No duplicate values
Example:
UserId INT PRIMARY KEY
2. FOREIGN KEY
- Creates a relationship between two tables
- Ensures values exist in the referenced table
Example:
UserId INT,
FOREIGN KEY (UserId) REFERENCES Users(UserId)
3. UNIQUE
- Ensures all values in a column are unique
- Allows only one
NULL(depends on DB)
Example:
Email VARCHAR(100) UNIQUE
4. NOT NULL
- Prevents
NULLvalues in a column
Example:
Name VARCHAR(50) NOT NULL
5. CHECK
- Validates data using a condition
Example:
Age INT CHECK (Age >= 18)
6. DEFAULT
- Assigns a default value if none is provided
Example:
CreatedDate DATETIME DEFAULT GETDATE()
Simple real-world example
CREATE TABLE Users (
UserId INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE NOT NULL,
Age INT CHECK (Age >= 18),
CreatedDate DATETIME DEFAULT GETDATE()
);
Here:
UserIdmust be uniqueEmailcannot be duplicated or emptyAgemust be 18 or aboveCreatedDateauto-fills if not provided
In one line:
Database constraints enforce rules to keep your data correct and trustworthy.