SQL and Databases on schema design and migrations
Store each fact once
- Normalizing means each fact lives in one place. A user's email sits in users only.
- Copies drift: change the email in one table and the other copies are now wrong.
- Other tables point at the row by id, and a join brings the fact back.
Relationships decide the tables
- One to many: a user has many orders. The user_id column goes on orders, the many side.
- Many to many: orders and products. Add a table, order_items, with one row per pair.
- Columns like product1, product2, product3 are a list. Make them rows in another table.
Denormalize only for a measured reason
- A stored copy or total, like users.order_count, saves a join or a count on every read.
- Now every write must update both places, or they disagree.
- Do it when a real query is too slow and an index did not fix it.
jsonb holds the parts with no fixed shape
- jsonb stores JSON in a binary form that is fast to query. Prefer it to the json type.
- A GIN index lets queries search for keys and values inside the documents.
- Keep anything you join on or constrain as a real column.
Change the schema in steps old code survives
- During a deploy, old and new code run against the same database.
- Expand: add the new column or table. Old code keeps working.
- Migrate: write to both, copy old rows across in small batches, then switch reads.
- Contract: drop the old column only when no running code uses it.
- Expandadd the new column
- Write bothnew code fills old and new
- Backfillcopy old rows in batches
- Switch readsread the new column
- Contractdrop the old column
Some schema changes lock the table
- Most ALTER TABLE forms take a lock that blocks all reads and writes while they run.
- Adding a column is quick, even with a constant default. No rows are rewritten.
- Changing a column's type usually rewrites the whole table.
- Add a foreign key as NOT VALID, then validate it. The slow check then allows writes.
SET lock_timeout = '5s';
ALTER TABLE orders ADD COLUMN coupon_id bigint;
ALTER TABLE orders ADD CONSTRAINT orders_coupon_fk
FOREIGN KEY (coupon_id) REFERENCES coupons (id)
NOT VALID;
ALTER TABLE orders
VALIDATE CONSTRAINT orders_coupon_fk;