Loading lessons...
SQL Constraints
SQL Constraints
Constraints are rules applied to columns. They limit what data can be stored, keeping the table correct.
The main constraints
| Constraint | Rule |
|---|---|
| NOT NULL | column cannot be empty |
| UNIQUE | all values must be different |
| PRIMARY KEY | uniquely identifies each row |
| FOREIGN KEY | links to another table's key |
| CHECK | values must satisfy a condition |
| DEFAULT | gives a value if none is provided |
Syntax examples
In the column definition:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
Age int CHECK (Age >= 0)
);
Or after the columns:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255),
PRIMARY KEY (ID)
);
Why use them?
- Prevent bad data (negative ages, duplicate IDs).
- Keep related tables consistent.
- Make data predictable for your apps.
Add a constraint later
ALTER TABLE Persons
ADD CHECK (Age >= 0);
TL;DR
- Constraints are rules on columns.
- NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.
- They stop invalid data from entering tables.