Relationships and invariants belong in the model#
users(id PRIMARY KEY, email UNIQUE, created_at)
orders(id PRIMARY KEY, user_id REFERENCES users(id), status, created_at)Tables give entities a defined shape. Primary keys establish identity, foreign keys can preserve references, and constraints reject invalid states. A join answers questions such as “orders for this user” without copying the entire user into every order.
Structure buys correctness and query flexibility#
Transactions group related changes. Indexes accelerate chosen queries. SQL makes filtering, joining, grouping, and evolving analysis expressive. Those capabilities still require schema evolution, index discipline, capacity planning, and careful distribution at scale.
| Mechanism | What it protects or enables | Cost/question |
|---|---|---|
| Foreign key | Referenced row exists | Write coordination and lifecycle |
| Unique constraint | No duplicate business key | Contention and index work |
| Join | Related data without duplication | Plan and data-volume sensitivity |
| Transaction | Cross-row invariant | Isolation and contention choices |
Related practice problems
Use the manifest-backed prompts below to apply this lesson in a complete design.
- PostgreSQL data definitionPostgreSQL Documentation