What rule should the database enforce?
Tables and constraints encode assumptions that query authors otherwise have to guess. Data changes introduce another question: what must happen atomically, and what happens when a write conflicts or repeats?
Decision reference
| Operation | Start with |
|---|---|
| Define or change structure | CREATE / ALTER TABLE |
| Enforce identity or relationships | PRIMARY KEY / UNIQUE / FOREIGN KEY |
| Enforce row rules | NOT NULL / CHECK |
| Change rows | INSERT / UPDATE / DELETE |
| Handle conflicts | ON CONFLICT / MERGE; engine-specific semantics |
In this chapter
- Keys, constraints & defaultsEncode data rules in the database and understand what each constraint guarantees.
- CREATE, ALTER, DROP & TRUNCATEDistinguish changing a table's structure from changing its rows.
- INSERT, UPDATE & DELETEChange exactly the intended rows and inspect the results.
- Upserts & MERGEDefine how incoming records interact with existing keys.
- MERGE, late updates, and replay correctnessUse source versions and tombstones to prevent stale updates and duplicate effects.
Check the invariant
For every constraint or write pattern, state the rule the database is protecting. Then ask what happens on duplicate input, partial failure, or a retry.