1.8 KiB
1.8 KiB
name, description
| name | description |
|---|---|
| db-migration-safety | Use when designing database schemas, writing schema migrations, optimizing slow SQL queries, or planning zero-downtime database changes. |
Safe Database Migrations & SQL Optimization
Purpose
Ensure all database schema changes execute safely in production without blocking table locks, downtime, or data corruption, while optimizing query execution plans.
Safe Migration Rules (Zero-Downtime Pattern)
1. Adding Columns
- Safe: Adding nullable columns or columns with default values (PostgreSQL >= 11 handles constant defaults instantly without table rewrites).
- Unsafe: Adding
NOT NULLwithout a default on large tables (locks table). Use a 3-step migration: add nullable column\tobackfill data in batches\toaddNOT NULLconstraint withNOT VALIDthenVALIDATE CONSTRAINT.
2. Renaming & Dropping Columns
- Never rename/drop in one step: Old application instances running during deployment will crash when the column disappears.
- Expand/Contract Pattern:
- Add new column.
- Write to both old and new columns in application code.
- Backfill existing rows.
- Switch reads to new column.
- Stop writing to old column.
- Drop old column.
3. Adding Indexes Safely
- In PostgreSQL: Always use
CREATE INDEX CONCURRENTLY(orDROP INDEX CONCURRENTLY) to avoid acquiring exclusive write locks. - In MySQL: Use
ALGORITHM=INPLACE, LOCK=NONEor gh-ost / pt-online-schema-change for heavy tables.
SQL Performance & Query Optimization
- Analyze queries with
EXPLAIN (ANALYZE, BUFFERS)(Postgres) orEXPLAIN ANALYZE(MySQL). - Eliminate Seq Scans / Full Table Scans on high-cardinality tables by adding composite indexes matching query
WHEREandORDER BYpredicates. - Prevent N+1 queries by leveraging
JOIN, eager loading, or DataLoader patterns.