Constraints & Integrity: Concept
Module: Schema Design & Advanced DDL
Database constraints are rules enforced by the database engine itself. They validate data before it's written to disk. If data violates a constraint, the database rejects the entire transaction—no partial writes, no corrupted state.
Think of constraints as bouncers at a nightclub. They check everyone at the door. If you don't meet the requirements, you don't get in. No exceptions. No matter how convincing your story, no matter who sent you, the rules are the rules.
Application validation is like asking people nicely to follow the rules. Most will, but some won't. Some will find ways around it. Some will bypass your application entirely and write directly to the database. Constraints don't ask—they enforce.
Here's the hierarchy of data validation:
**Level 1: Application Validation (Weakest)**
- User-friendly error messages
- Can be bypassed (direct SQL, API exploits, bugs)
- Not enforced for batch imports or admin tools
- Example: JavaScript checks if email contains @
**Level 2: Database Constraints (Strong)**
- Enforced for all writes, no exceptions
- Cannot be bypassed without dropping the constraint
- Atomic—either all constraints pass or transaction rolls back
- Example: UNIQUE constraint on email column
**Level 3: Application + Database (Best)**
- Application validation for user experience (immediate feedback)
- Database constraints for data integrity (last line of defense)
- Example: JavaScript checks email format, database ensures uniqueness
You always want Level 3. Application validation gives users immediate feedback. Database constraints ensure data integrity even when application validation fails or is bypassed.
## Six Types of Constraints
### 1. PRIMARY KEY - Unique Identifier
Every table needs a way to uniquely identify each row. That's the primary key.
**What it does:**
- Ensures every row has a unique identifier
- Automatically creates a UNIQUE constraint
- Automatically creates a NOT NULL constraint
- Creates an index for fast lookups
**Example:**
```sql
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY, -- Auto-incrementing unique ID
email VARCHAR(255),
name VARCHAR(100)
);
```
**Rules:**
- Only one primary key per table
- Can be a single column or multiple columns (composite key)
- Cannot contain NULL values
- Should be immutable (never changes)