Table
Constraints in SQL
Learn how PRIMARY KEY, FOREIGN KEY, and UNIQUE constraints enforce data integrity and keep your databases reliable.
What Are Constraints?
Constraints are rules you define on a table's columns that the database enforces automatically. They prevent invalid data from ever entering your tables, acting like guardrails for your data.
Why Constraints Matter
The Big Three Constraints
PRIMARY KEY: The Row ID
PRIMARY KEY Syntax
FOREIGN KEY: The Link
FOREIGN KEY Syntax
UNIQUE: No Duplicates
UNIQUE Syntax
PRIMARY KEY vs UNIQUE
| PRIMARY KEY | UNIQUE | |
|---|---|---|
| Allows NULLs? | No | Yes |
| How many per table? | Exactly 1 | Many |
| Enforces uniqueness? | Yes | Yes |
| Creates an index? | Yes | Yes |
| Can be referenced by FK? | Yes | Yes |
How to Apply Constraints
Example 1: Simple Table
A school needs a courses table. Each course has a unique ID, a name, and a department code. No two courses should share the same name.
Example 2: Linked Tables
Now add a grades table that links students to courses. Both student_id and course_id must reference existing records.
Example 3: Full Schema
Common Mistakes
Summary Table
| Feature | PRIMARY KEY | FOREIGN KEY | UNIQUE |
|---|---|---|---|
| Purpose | Row identity | Link tables | No duplicates |
| NULLs? | No | Yes | Yes |
| Per table | 1 | Many | Many |
| Uniqueness | Yes | No | Yes |
| References? | Is referenced | References PK | Can be referenced |
Question 1 of 5
Which constraint uniquely identifies each row and does not allow NULLs?
Question 2 of 5
How many PRIMARY KEY constraints can a single table have?
Question 3 of 5
What does a FOREIGN KEY enforce?
Question 4 of 5
Consider this statement:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
tracking_num VARCHAR(50) UNIQUE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
Which of the following INSERTs would the database accept?
Question 5 of 5
A table needs columns for id, email, and phone. Both email and phone must be unique. Which setup is correct?