When to Denormalise Your Schema
A practical guide to when to Denormalise Your Schema — tips, best practices, and real-world examples.
# When to Denormalise Your Schema
Sometimes breaking normalization rules is the right choice.
## What Is Denormalisation?
Storing redundant data to optimize reads.
## When to Denormalise
1. **Expensive calculations** — store computed values
2. **Frequent aggregations** — pre-compute counts
3. **Slow joins** — duplicate foreign data
## Example: Post Counts
### Normalised (Slow)
```sql
SELECT COUNT(*) FROM posts WHERE user_id = 1;
```
Runs on every page load!
### Denormalised (Fast)
```sql
-- Add column
ALTER TABLE users ADD COLUMN post_count INTEGER DEFAULT 0;
-- Update on post create/delete
UPDATE users SET post_count = post_count + 1 WHERE id = 1;
```
## Trade-offs
- **Writes become complex**
- **Data can be inconsistent**
- **More storage needed**
## Best Practices
1. Keep source of truth normalized
2. Update denormalised data immediately
3. Have reconciliation jobs for safety
## Conclusion
Denormalisation is a tool, not a sin. Use it strategically!
Sometimes breaking normalization rules is the right choice.
## What Is Denormalisation?
Storing redundant data to optimize reads.
## When to Denormalise
1. **Expensive calculations** — store computed values
2. **Frequent aggregations** — pre-compute counts
3. **Slow joins** — duplicate foreign data
## Example: Post Counts
### Normalised (Slow)
```sql
SELECT COUNT(*) FROM posts WHERE user_id = 1;
```
Runs on every page load!
### Denormalised (Fast)
```sql
-- Add column
ALTER TABLE users ADD COLUMN post_count INTEGER DEFAULT 0;
-- Update on post create/delete
UPDATE users SET post_count = post_count + 1 WHERE id = 1;
```
## Trade-offs
- **Writes become complex**
- **Data can be inconsistent**
- **More storage needed**
## Best Practices
1. Keep source of truth normalized
2. Update denormalised data immediately
3. Have reconciliation jobs for safety
## Conclusion
Denormalisation is a tool, not a sin. Use it strategically!
Database
Performance