Skip to content
OpenAgentsbeta
text
1# Safe recipes
2
3## Add a NOT NULL column
4
5Unsafe: `ADD COLUMN x text NOT NULL DEFAULT 'a'` on an old engine rewrites the table.
6
7Safe:
8
91. Add the column nullable, no default.
102. Deploy code that writes it on every new row.
113. Backfill existing rows in batches.
124. Add the `NOT NULL` constraint, validated separately where the engine allows.
13
14## Rename a column
15
16Never rename in place while code is running.
17
181. Add the new column.
192. Deploy code that writes both and reads the new one, falling back to the old.
203. Backfill.
214. Deploy code that only uses the new one.
225. Drop the old column, in a later release.
23
24## Drop a column
25
261. Deploy code that never reads or writes it. Confirm in production over some days.
272. Drop it.
28
29Never in one step. The old running instances will still be selecting it.
30
31## Add an index
32
33Use the concurrent form where available.
34
35```sql
36CREATE INDEX CONCURRENTLY idx_name ON table (col);
37```
38
39It cannot run inside a transaction, takes longer, and can leave an invalid index if it
40fails. Check validity afterwards and drop and retry if needed.
41
42## Change a column type
43
44Usually a table rewrite. Treat it as a rename:
45
461. Add a new column of the new type.
472. Dual-write.
483. Backfill in batches.
494. Switch reads.
505. Drop the old column later.
51
52## Add a foreign key
53
54Adding it validated locks both tables while it checks every row.
55
561. Add the constraint `NOT VALID`. It applies to new rows only, and takes a brief lock.
572. `VALIDATE CONSTRAINT` separately. This takes a weaker lock and can run for a while.
58
59## Delete a lot of rows
60
61Never one statement.
62
63```sql
64-- Repeat until zero rows affected, pausing between batches.
65DELETE FROM t WHERE id IN (
66 SELECT id FROM t WHERE <predicate> LIMIT 5000
67);
68```
69
70Watch replication lag between batches, and stop if it grows.
71

Keyboard shortcuts

Focus search
/
Go to Explore
ge
Go to Home
gh
Go to Tags
gt
Go to Collections
gc
Show this help
?
Close suggestions or this dialog
Esc