Lesson 32 +10 XP

SQL Constraints

SQL Constraints

Constraints are rules applied to columns. They limit what data can be stored, keeping the table correct.

The main constraints

ConstraintRule
NOT NULLcolumn cannot be empty
UNIQUEall values must be different
PRIMARY KEYuniquely identifies each row
FOREIGN KEYlinks to another table's key
CHECKvalues must satisfy a condition
DEFAULTgives 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.