What are Data Integrity Constraints?
All Constraints Summary
| Constraint | Purpose | Example |
|---|---|---|
| PRIMARY KEY | Unique identifier | user_id |
| FOREIGN KEY | Link tables | customer_id references customers |
| UNIQUE | No duplicates | email, username |
| NOT NULL | Required field | name, email |
| CHECK | Validate values | age >= 18, price > 0 |
5 rows
Constraints are rules that keep your data correct and reliable. They prevent bad data from entering your database.
Simple analogy: Like spell-check and grammar-check for your database - catches mistakes before they happen.
All Constraints Together
All Constraints Summary
| Constraint | Purpose | Example |
|---|---|---|
| PRIMARY KEY | Unique identifier | user_id |
| FOREIGN KEY | Link tables | customer_id references customers |
| UNIQUE | No duplicates | email, username |
| NOT NULL | Required field | name, email |
| CHECK | Validate values | age >= 18, price > 0 |
5 rows
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
age INTEGER CHECK (age >= 18),
account_balance DECIMAL(10, 2) CHECK (account_balance >= 0)
);What each constraint does:
- PRIMARY KEY: Unique identifier (no duplicates, not empty)
- UNIQUE: No two users can have same username or email
- NOT NULL: Username and email are required
- CHECK: Age must be 18+, balance cannot be negative
Why Constraints Matter
All Constraints Summary
| Constraint | Purpose | Example |
|---|---|---|
| PRIMARY KEY | Unique identifier | user_id |
| FOREIGN KEY | Link tables | customer_id references customers |
| UNIQUE | No duplicates | email, username |
| NOT NULL | Required field | name, email |
| CHECK | Validate values | age >= 18, price > 0 |
5 rows
Without constraints:
- Can create two users with same email (confusion!)
- Can have age = -5 (impossible!)
- Can have empty usernames (incomplete data!)
With constraints:
- Database blocks bad data automatically
- Keeps data clean and reliable
- Prevents mistakes
Summary
All Constraints Summary
| Constraint | Purpose | Example |
|---|---|---|
| PRIMARY KEY | Unique identifier | user_id |
| FOREIGN KEY | Link tables | customer_id references customers |
| UNIQUE | No duplicates | email, username |
| NOT NULL | Required field | name, email |
| CHECK | Validate values | age >= 18, price > 0 |
5 rows
Constraints = Rules to protect data quality
- PRIMARY KEY: Unique ID
- FOREIGN KEY: Connect tables
- UNIQUE: No duplicates
- NOT NULL: Required fields
- CHECK: Validate values
All working together to keep your database perfect!