3. Constraints
Constraints enforce rules on the data in a database table to maintain integrity and accuracy.
1. NOT NULL Constraint
Ensures that a column cannot store NULL values.
- Used for mandatory fields (e.g., Name, Email).
Example:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL, -- Name cannot be NULL
Email VARCHAR(100) NOT NULL
);
| UserID (PK) | Name | |
|---|---|---|
| 1 | John | john@example.com |
| 2 | NULL | jane@example.com |
2. UNIQUE Constraint
Ensures that all values in a column are distinct.
- Can be used on multiple columns.
- Allows one NULL value per column.
Example:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE NOT NULL -- Ensures each email is unique
);
| UserID (PK) | |
|---|---|
| 1 | john@example.com |
| 2 | jane@example.com |
| 3 | john@example.com |
3. CHECK Constraint
Ensures values meet a specific condition.
- Used for data validation (e.g., age must be positive).
Example:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Age INT CHECK (Age >= 18) -- Ensures age is 18 or older
);
| EmployeeID (PK) | Age |
|---|---|
| 1 | 25 |
| 2 | 17 |
4. DEFAULT Constraint
Assigns a default value when no value is provided.
- Ensures consistent data.
Example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
Status VARCHAR(20) DEFAULT 'Pending' -- Default order status
);
| OrderID (PK) | Status |
|---|---|
| 1 | Shipped |
| 2 | Pending |
Key Takeaways
- NOT NULL → Prevents NULL values.
- UNIQUE → Ensures distinct values.
- CHECK → Restricts values based on a condition.
- DEFAULT → Provides a fallback value.