@vstlmkh/designing-databases 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,375 @@
1
+ # Migrations
2
+
3
+ Load in Workflow C — writing, reviewing, or de-risking a schema change.
4
+
5
+ ## Contents
6
+
7
+ - The rule that makes migrations safe
8
+ - Expand / contract
9
+ - Lock-safe DDL: PostgreSQL
10
+ - Lock-safe DDL: MySQL / InnoDB
11
+ - Online schema change tools
12
+ - Backfills
13
+ - Engine-agnostic runners: Flyway, Liquibase, Atlas, golang-migrate
14
+ - Python: Alembic, Django
15
+ - Node/TypeScript: Prisma, TypeORM, Knex, Drizzle
16
+ - PHP: Laravel, Doctrine
17
+ - Review checklist
18
+
19
+ ## The rule that makes migrations safe
20
+
21
+ **During a deploy, the old code and the new schema run at the same time.** Every
22
+ migration must be compatible with the application version already running, and
23
+ every application version must be compatible with the schema before and after.
24
+ That single constraint produces expand/contract, and it is why "just rename the
25
+ column" is never a one-step change.
26
+
27
+ Second rule: a migration must never hold a lock longer than the slowest query on
28
+ the table. Always set a lock timeout and retry rather than queue.
29
+
30
+ ## Expand / contract
31
+
32
+ | Change | Steps |
33
+ |---|---|
34
+ | Rename a column | add new → write both → backfill → read new → stop writing old → drop old |
35
+ | Change a type | add new column of the new type → dual-write → backfill in batches → switch reads → drop old |
36
+ | Add a required column | add nullable → backfill → add `NOT NULL` via validated CHECK → set default |
37
+ | Drop a column | stop reading in code → deploy → stop writing → deploy → drop |
38
+ | Split/merge tables | create new → dual-write → backfill → switch reads → retire old |
39
+
40
+ Each arrow is a separate deploy. The migration that drops something must land at
41
+ least one release after the code that stopped using it.
42
+
43
+ ## Lock-safe DDL: PostgreSQL
44
+
45
+ Most `ALTER TABLE` forms take `ACCESS EXCLUSIVE`, which blocks reads *and*
46
+ writes. The danger is not the duration of the DDL but the lock queue: a DDL
47
+ waiting behind one long query blocks every statement that arrives after it.
48
+
49
+ ```sql
50
+ SET lock_timeout = '3s'; -- fail fast instead of queueing; retry in a loop
51
+ SET statement_timeout = '0'; -- but let the work itself finish
52
+ ```
53
+
54
+ | Operation | Cost | Safe form |
55
+ |---|---|---|
56
+ | `ADD COLUMN` (no default / constant default) | metadata only (PG 11+) | direct |
57
+ | `ADD COLUMN … DEFAULT now()` / `gen_random_uuid()` | full table rewrite (volatile) | add nullable → backfill → set default |
58
+ | `SET NOT NULL` | full scan under ACCESS EXCLUSIVE | `ADD CONSTRAINT … CHECK (col IS NOT NULL) NOT VALID` → `VALIDATE CONSTRAINT` → `SET NOT NULL` (scan skipped, PG 12+) |
59
+ | `ADD FOREIGN KEY` / `ADD CHECK` | scan + blocking | add `NOT VALID`, then `VALIDATE CONSTRAINT` (SHARE UPDATE EXCLUSIVE, writes allowed) |
60
+ | `ALTER COLUMN … TYPE` | rewrites table + indexes | expand/contract; exception: binary-coercible types (e.g. `varchar(50)`→`varchar(100)`) |
61
+ | `CREATE INDEX` | blocks writes for the build | `CREATE INDEX CONCURRENTLY` (outside a transaction) |
62
+ | `DROP INDEX` | brief ACCESS EXCLUSIVE | `DROP INDEX CONCURRENTLY` |
63
+ | Add a primary key | blocking | `CREATE UNIQUE INDEX CONCURRENTLY`, then `ADD CONSTRAINT … PRIMARY KEY USING INDEX` |
64
+ | `SET DEFAULT` / `DROP DEFAULT` | metadata only | direct |
65
+
66
+ `CREATE INDEX CONCURRENTLY` cannot run inside a transaction block, takes roughly
67
+ twice as long, and on failure leaves an invalid index that still costs writes:
68
+
69
+ ```sql
70
+ SELECT relname, indisvalid FROM pg_index i
71
+ JOIN pg_class c ON c.oid = i.indexrelid WHERE NOT indisvalid;
72
+ -- then: DROP INDEX CONCURRENTLY <name>; and retry
73
+ ```
74
+
75
+ ## Lock-safe DDL: MySQL / InnoDB
76
+
77
+ State the algorithm explicitly. If the server cannot honour it, the statement
78
+ fails — which is far better than silently copying a 300 GB table.
79
+
80
+ ```sql
81
+ ALTER TABLE orders ADD COLUMN note VARCHAR(255), ALGORITHM=INSTANT;
82
+ ALTER TABLE orders ADD INDEX idx_orders_status (status), ALGORITHM=INPLACE, LOCK=NONE;
83
+ SET SESSION lock_wait_timeout = 3; -- metadata-lock guard
84
+ ```
85
+
86
+ | Operation | Algorithm | Notes |
87
+ |---|---|---|
88
+ | Add / drop / rename column | `INSTANT` (MySQL 8.0.12+ / 8.0.29 for drop) | capped at 64 row versions before a rebuild is required; not for COMPRESSED tables |
89
+ | Set / drop column default | `INSTANT` | data-dictionary only |
90
+ | Add / drop / rename index | `INPLACE`, `LOCK=NONE` | builds without blocking DML |
91
+ | Extend `VARCHAR` within the same length-byte class (≤255 or ≥256) | `INPLACE`, `LOCK=NONE` | crossing 255→256 needs `COPY` |
92
+ | `MODIFY … NOT NULL` | `INPLACE` | requires strict SQL mode; fails if NULLs exist |
93
+ | Add primary key | `INPLACE` | rebuilds, but online |
94
+ | Change column data type | `COPY` | blocks DML — use gh-ost / pt-osc |
95
+ | Shrink `VARCHAR`, drop primary key, add `STORED` generated column | `COPY` | blocks DML |
96
+ | Add foreign key | `INPLACE` only with `foreign_key_checks=0` | otherwise `COPY` |
97
+
98
+ Even an `INSTANT` DDL needs a metadata lock, which waits for open transactions on
99
+ the table and blocks everything behind it meanwhile. Check
100
+ `SHOW PROCESSLIST` / `performance_schema.metadata_locks` before firing one.
101
+
102
+ ## Online schema change tools
103
+
104
+ When InnoDB forces a `COPY`, or the table is too large for a single ALTER:
105
+
106
+ ```bash
107
+ # gh-ost: binlog-based, no triggers, pausable and throttleable
108
+ gh-ost --host=replica.example.com --database=shop --table=orders \
109
+ --alter="MODIFY COLUMN total DECIMAL(14,2) NOT NULL" \
110
+ --max-load=Threads_running=25 --critical-load=Threads_running=100 \
111
+ --chunk-size=1000 --throttle-control-replicas=r1,r2 \
112
+ --postpone-cut-over-flag-file=/tmp/cutover.flag \
113
+ --execute # without --execute it is a dry run — always dry-run first
114
+ ```
115
+
116
+ ```bash
117
+ # pt-online-schema-change: trigger-based; simpler, but triggers add write overhead
118
+ pt-online-schema-change --alter "ADD INDEX idx_status (status)" \
119
+ D=shop,t=orders --max-lag=1 --dry-run
120
+ ```
121
+
122
+ PostgreSQL rarely needs these (concurrent index builds plus `NOT VALID`
123
+ constraints cover most cases); for a true table rewrite without downtime use
124
+ logical replication into a new table, or `pg_repack` for bloat.
125
+
126
+ ## Backfills
127
+
128
+ Never one statement over the whole table: PostgreSQL doubles the heap and stalls
129
+ autovacuum; InnoDB grows the undo log until commit, and a rollback can take
130
+ longer than the update.
131
+
132
+ ```sql
133
+ -- Batch by primary key, one transaction per chunk, with a pause between chunks
134
+ UPDATE orders SET status_code = status
135
+ WHERE id BETWEEN :lo AND :hi AND status_code IS NULL;
136
+ ```
137
+
138
+ Rules: bound each batch (1k–10k rows), commit per batch, make it resumable and
139
+ idempotent (`WHERE new_col IS NULL`), log progress, throttle on replication lag,
140
+ and run it as a job — not inside the migration that holds the DDL lock.
141
+
142
+ ## Engine-agnostic runners: Flyway, Liquibase, Atlas, golang-migrate
143
+
144
+ **Flyway** — versioned SQL files, applied in version order, checksummed in
145
+ `flyway_schema_history`.
146
+
147
+ ```bash
148
+ flyway migrate # apply pending
149
+ flyway info # what is applied / pending
150
+ flyway validate # checksums vs history
151
+ flyway repair # realign checksums after a legitimate file change
152
+ flyway baseline # adopt an existing database at a version
153
+ ```
154
+
155
+ Naming: `V2__add_orders_index.sql` (versioned), `R__refresh_views.sql`
156
+ (repeatable, re-applied whenever the checksum changes), `U2__…` (undo, paid
157
+ editions). **Never edit an applied migration** — the checksum mismatch fails
158
+ every subsequent run on every environment; ship a new version instead.
159
+ Put `CREATE INDEX CONCURRENTLY` in a script marked non-transactional
160
+ (`executeInTransaction=false` in the script's `.conf`).
161
+
162
+ **Liquibase** — changelog of changesets, identified by `author:id:filepath` and
163
+ tracked in `DATABASECHANGELOG` with a checksum.
164
+
165
+ ```bash
166
+ liquibase update # apply pending changesets
167
+ liquibase status --verbose
168
+ liquibase update-sql # print SQL without applying — review gate
169
+ liquibase rollback <tag> | rollback-count 1
170
+ liquibase changelog-sync # mark changesets applied (object already exists)
171
+ liquibase update-testing-rollback
172
+ ```
173
+
174
+ Write an explicit `<rollback>` for anything Liquibase cannot auto-reverse, use
175
+ `contexts`/`labels` to scope environment-specific changesets, and preconditions
176
+ to make a changeset self-checking. Changing an applied changeset's body breaks
177
+ the checksum — add a new changeset.
178
+
179
+ **Atlas** — declarative schema or versioned migrations, diffed against a
180
+ throwaway *dev database*.
181
+
182
+ ```bash
183
+ atlas migrate diff add_orders_index \
184
+ --dir "file://migrations" --to "file://schema.hcl" --dev-url "docker://postgres/16/dev"
185
+ atlas migrate lint --dir "file://migrations" --dev-url "docker://postgres/16/dev" --latest 1
186
+ atlas migrate hash # after any manual edit to a migration file
187
+ atlas migrate apply --url "$DATABASE_URL"
188
+ ```
189
+
190
+ `atlas migrate lint` is a genuine CI gate: it flags destructive and
191
+ lock-dangerous changes. Atlas can emit concurrent index builds via the
192
+ `diff.concurrent_index` block in `atlas.hcl`. Always `migrate hash` after
193
+ editing a file by hand, or the directory integrity check fails.
194
+
195
+ **golang-migrate** — paired `up`/`down` SQL files.
196
+
197
+ ```bash
198
+ migrate create -ext sql -dir db/migrations -seq add_orders_index
199
+ migrate -path db/migrations -database "$DATABASE_URL" up
200
+ migrate -path db/migrations -database "$DATABASE_URL" down 1
201
+ migrate -path db/migrations -database "$DATABASE_URL" force 7 # clear a dirty state
202
+ ```
203
+
204
+ A failed migration leaves the database **dirty**; nothing else runs until you
205
+ inspect what actually applied and `force` the correct version. Statements run
206
+ inside a transaction by default — for `CREATE INDEX CONCURRENTLY`, disable it for
207
+ that migration (`x-no-transaction` / the driver's `x-multi-statement` settings).
208
+
209
+ ## Python: Alembic, Django
210
+
211
+ **Alembic**
212
+
213
+ ```bash
214
+ alembic revision --autogenerate -m "add orders status index"
215
+ alembic upgrade head
216
+ alembic downgrade -1
217
+ alembic current / history / heads
218
+ alembic merge heads # after two branches both created a head
219
+ ```
220
+
221
+ Autogenerate detects added/removed tables and columns, nullability, basic index
222
+ and FK changes, and (by default) type changes. It does **not** detect table or
223
+ column renames (they come out as drop+add — hand-edit them), unnamed
224
+ constraints, or server-default changes unless `compare_server_default=True`.
225
+ Always read the generated file before committing it.
226
+
227
+ Concurrent index build (otherwise Alembic wraps the migration in a transaction):
228
+
229
+ ```python
230
+ def upgrade():
231
+ with op.get_context().autocommit_block():
232
+ op.create_index("idx_orders_status", "orders", ["status"],
233
+ postgresql_concurrently=True)
234
+ ```
235
+
236
+ Use `op.batch_alter_table` for SQLite, and `op.execute` for anything the DSL
237
+ cannot express.
238
+
239
+ **Django**
240
+
241
+ ```bash
242
+ python manage.py makemigrations app
243
+ python manage.py sqlmigrate app 0042 # see the SQL before it runs — review gate
244
+ python manage.py migrate
245
+ python manage.py migrate app 0041 # revert to a previous migration
246
+ ```
247
+
248
+ ```python
249
+ from django.contrib.postgres.operations import AddIndexConcurrently
250
+
251
+ class Migration(migrations.Migration):
252
+ atomic = False # REQUIRED: CONCURRENTLY cannot run in a transaction
253
+ operations = [
254
+ AddIndexConcurrently("event", models.Index(fields=["tenant_id", "created_at"],
255
+ name="ev_tenant_created_idx")),
256
+ ]
257
+ ```
258
+
259
+ Keep schema and data migrations in separate files; give every `RunPython` a
260
+ `reverse_code` (or `migrations.RunPython.noop`); use the historical model from
261
+ `apps.get_model(...)`, never the imported model class. On MySQL, DDL commits
262
+ implicitly, so `atomic = True` buys you nothing there.
263
+
264
+ ## Node/TypeScript: Prisma, TypeORM, Knex, Drizzle
265
+
266
+ **Prisma**
267
+
268
+ ```bash
269
+ npx prisma migrate dev --name add_orders_index # DEV ONLY: needs a shadow database
270
+ npx prisma migrate deploy # production: applies pending, no drift check
271
+ npx prisma migrate status
272
+ npx prisma migrate resolve --applied <migration> # repair a failed production migration
273
+ npx prisma migrate diff --from-schema-datamodel … --to-schema-datasource …
274
+ npx prisma db push # prototyping only: no migration file
275
+ ```
276
+
277
+ The shadow database (created and dropped by `migrate dev`) requires `CREATEDB`
278
+ on PostgreSQL; on managed clouds that forbid it, provision one and set
279
+ `shadowDatabaseUrl`. Never run `migrate dev`, `db push` or `migrate reset`
280
+ against production. To customize DDL (concurrent index, `NOT VALID`), generate
281
+ the migration, then edit the SQL file before applying it.
282
+
283
+ **TypeORM**
284
+
285
+ ```bash
286
+ typeorm migration:generate -d src/data-source.ts src/migrations/AddOrdersIndex
287
+ typeorm migration:run -d src/data-source.ts
288
+ typeorm migration:revert -d src/data-source.ts
289
+ ```
290
+
291
+ `synchronize: true` silently drops and recreates columns to match entities —
292
+ acceptable only in a throwaway local database, never anywhere else. Generated
293
+ migrations are a starting point: they often emit a drop+add for a rename.
294
+
295
+ **Knex**
296
+
297
+ ```bash
298
+ knex migrate:make add_orders_index
299
+ knex migrate:latest
300
+ knex migrate:rollback --all
301
+ knex migrate:status
302
+ ```
303
+
304
+ Knex wraps each migration in a transaction; disable it for concurrent index
305
+ builds with `exports.config = { transaction: false }`.
306
+
307
+ **Drizzle**
308
+
309
+ ```bash
310
+ drizzle-kit generate # diff TS schema -> SQL migration file
311
+ drizzle-kit migrate # apply pending files
312
+ drizzle-kit push # prototyping only: apply directly, no file
313
+ drizzle-kit check # detect conflicting/corrupt migration metadata
314
+ ```
315
+
316
+ Use `generate` + `migrate` in production so the SQL is reviewable; `push` is for
317
+ local iteration. Rename detection is interactive at generate time — answer it, or
318
+ you get a drop+add that loses data.
319
+
320
+ ## PHP: Laravel, Doctrine
321
+
322
+ **Laravel**
323
+
324
+ ```bash
325
+ php artisan make:migration add_status_index_to_orders_table
326
+ php artisan migrate --pretend # print the SQL without running it — review gate
327
+ php artisan migrate
328
+ php artisan migrate:rollback --step=1
329
+ php artisan migrate:status
330
+ ```
331
+
332
+ ```php
333
+ Schema::table('orders', function (Blueprint $table) {
334
+ $table->string('status_code', 20)->nullable(); // additive, nullable first
335
+ });
336
+ // Concurrent index / NOT VALID constraints need raw SQL:
337
+ DB::statement('CREATE INDEX CONCURRENTLY idx_orders_status ON orders (status)');
338
+ ```
339
+
340
+ On MySQL, DDL commits implicitly: a migration that mixes schema changes with a
341
+ backfill cannot roll back the DDL if the backfill fails, leaving the database
342
+ half-migrated. Keep them in separate migrations. `->change()` on a column relies
343
+ on doctrine/dbal and can silently drop attributes it does not know about — review
344
+ the `--pretend` output. Never create an index inside a loop over records.
345
+
346
+ **Doctrine Migrations (Symfony)**
347
+
348
+ ```bash
349
+ php bin/console doctrine:migrations:diff # generate from entity mapping diff
350
+ php bin/console doctrine:migrations:migrate
351
+ php bin/console doctrine:migrations:migrate prev
352
+ php bin/console doctrine:migrations:status
353
+ php bin/console doctrine:migrations:execute --up 'DoctrineMigrations\Version20260101120000'
354
+ ```
355
+
356
+ Always review a `diff`: it round-trips the whole mapping and will happily emit
357
+ drops for tables it does not know about (`schema_filter` prevents this). Override
358
+ `isTransactional(): bool { return false; }` for `CREATE INDEX CONCURRENTLY`. Put
359
+ data changes in `postUp()` or a separate command, not in `up()` alongside DDL.
360
+
361
+ ## Review checklist
362
+
363
+ Run `python3 scripts/migration_lint.py <dir> --engine <engine>` first, then
364
+ judge what it cannot:
365
+
366
+ - [ ] Is every statement compatible with the currently-deployed application code?
367
+ - [ ] Is anything destructive or renaming? If so, is it split across releases?
368
+ - [ ] What lock does each statement take, and for how long on production volume?
369
+ - [ ] Is there a `lock_timeout` / `lock_wait_timeout` guard?
370
+ - [ ] Are index builds concurrent / `LOCK=NONE`?
371
+ - [ ] Are constraints added `NOT VALID` and validated separately (PostgreSQL)?
372
+ - [ ] Are backfills batched, resumable, and outside the DDL migration?
373
+ - [ ] Does the down path exist and actually work — and is data loss acceptable?
374
+ - [ ] Has it been run against a production-sized copy, with timings recorded?
375
+ - [ ] Does it change replication-sensitive objects (large rewrites → lag)?
@@ -0,0 +1,252 @@
1
+ # Query tuning
2
+
3
+ Load in Workflow B — a query, endpoint, or report that is too slow.
4
+
5
+ ## Contents
6
+
7
+ - How the engine executes a query
8
+ - Getting a plan worth reading
9
+ - The five fields that matter
10
+ - Access paths
11
+ - Join algorithms and how they fail
12
+ - Sargability
13
+ - Query anti-patterns and their rewrites
14
+ - Statistics
15
+ - Memory and spills
16
+ - Parameter sniffing and plan regressions
17
+ - The diagnostic loop
18
+
19
+ ## How the engine executes a query
20
+
21
+ Four phases: parse (syntax, catalog lookups, permissions) → rewrite (flatten
22
+ subqueries, fold constants, drop `WHERE 1=1`) → cost-based optimization (enumerate
23
+ physical plans, score each from catalog statistics, pick the cheapest) → execute
24
+ (pull pages from the buffer pool, read from disk on a miss).
25
+
26
+ Cost is an artificial unit, not milliseconds. PostgreSQL's formula weighs
27
+ sequential page fetches (`seq_page_cost = 1.0`), random page fetches
28
+ (`random_page_cost = 4.0`), and CPU per tuple/operator. That 4:1 ratio assumes
29
+ spinning disks; on SSD/NVMe set `random_page_cost` to 1.1–1.5, or the planner
30
+ will keep rejecting correct index plans.
31
+
32
+ ## Getting a plan worth reading
33
+
34
+ ```sql
35
+ -- PostgreSQL: estimates + reality + I/O + settings that influenced the plan
36
+ EXPLAIN (ANALYZE, BUFFERS, SETTINGS, WAL, FORMAT JSON) <query>;
37
+
38
+ -- MySQL 8.0.18+
39
+ EXPLAIN ANALYZE <query>;
40
+ EXPLAIN FORMAT=TREE <query>; -- plan shape without executing
41
+ EXPLAIN FORMAT=JSON <query>; -- machine-readable, feeds explain_audit.py
42
+ ```
43
+
44
+ `EXPLAIN` alone prints estimates — the very thing that is usually wrong. Always
45
+ `ANALYZE`, and remember it **executes** the statement: wrap any `INSERT`/`UPDATE`/
46
+ `DELETE` in `BEGIN; … ROLLBACK;`.
47
+
48
+ Run `python3 scripts/explain_audit.py plan.json` on the JSON output: it does the
49
+ loop multiplication, the estimate/actual ratios, the self-time attribution and
50
+ the spill detection that are tedious and error-prone to do by eye.
51
+
52
+ ## The five fields that matter
53
+
54
+ | Field | Meaning | Warning sign |
55
+ |---|---|---|
56
+ | Node Type | physical algorithm | `Seq Scan` on a multi-million row table |
57
+ | Actual Time | `startup..total` **per loop**, ms | high startup on sorts; high total on leaves |
58
+ | Actual vs Plan Rows | estimate accuracy | off by ≥10x → the plan shape is probably wrong |
59
+ | Loops | executions of this node | the multiplier everyone forgets |
60
+ | Buffers | `shared hit` / `read` / `dirtied` | high `read` = real disk I/O |
61
+
62
+ **The loop trap**: a node showing `(actual time=0.050..0.080 rows=1 loops=500000)`
63
+ did not take 0.08 ms. It took 0.080 × 500,000 = 40 seconds. Total rows likewise
64
+ multiply by `loops`. PostgreSQL prints per-loop averages; misreading this is the
65
+ single most common plan-reading error.
66
+
67
+ ## Access paths
68
+
69
+ - **Seq Scan / full table scan** — reads every page, filters every row. Correct
70
+ for tiny tables and for queries needing >20–40% of a large one (sequential I/O
71
+ beats random navigation). Wrong when the predicate is selective: missing index,
72
+ non-sargable predicate, or a type mismatch.
73
+ - **Index Scan** — descend the tree, then fetch each matching row from the
74
+ heap/clustered index. Optimal for small result sets (1–100 rows); degenerates
75
+ into random I/O when matches are many and scattered.
76
+ - **Index Only Scan** — every needed column is in the index. PostgreSQL still
77
+ checks the visibility map; `Heap Fetches > 0` means it is not really index-only
78
+ (run `VACUUM (ANALYZE)`).
79
+ - **Bitmap Index Scan + Bitmap Heap Scan** (PostgreSQL) — for hundreds to tens of
80
+ thousands of matches: build a bitmap of candidate pages, sort it, read the heap
81
+ in physical order. Converts random I/O into sequential. If the bitmap outgrows
82
+ `work_mem` it degrades to *lossy* (page-level), and every row on those pages is
83
+ re-checked.
84
+
85
+ ## Join algorithms and how they fail
86
+
87
+ | Algorithm | Best for | Fails when |
88
+ |---|---|---|
89
+ | **Nested Loop** | small outer side + indexed inner side | the outer cardinality was underestimated — 5 expected rows become 200,000 index seeks |
90
+ | **Hash Join** | large unsorted inputs, equality conditions only | the build side exceeds `work_mem` / `join_buffer_size` and spills into multiple batches |
91
+ | **Merge Join** | inputs already sorted on the join key (via indexes) | inputs need explicit sorts; many-to-many duplicates force repeated rewinds |
92
+
93
+ Almost every pathological join plan traces back to a cardinality misestimate, not
94
+ to the algorithm choice. Fix the statistics before overriding the planner.
95
+
96
+ ## Sargability
97
+
98
+ A predicate is sargable (Search-ARGument-able) when the engine can navigate the
99
+ B-tree directly to satisfy it. Transformations on the column destroy that.
100
+
101
+ ```sql
102
+ -- Function on the column
103
+ WHERE LOWER(email) = 'alice@example.com' -- scan
104
+ WHERE email = 'alice@example.com' -- seek (or index LOWER(email))
105
+
106
+ -- Date truncation
107
+ WHERE DATE(created_at) = '2024-03-15' -- scan
108
+ WHERE created_at >= '2024-03-15'
109
+ AND created_at < '2024-03-16' -- seek, half-open range
110
+
111
+ -- Arithmetic on the column (the optimizer does not do algebra for you)
112
+ WHERE balance - 50 < 100 -- scan
113
+ WHERE balance < 150 -- seek
114
+
115
+ -- Type mismatch; phone_number is VARCHAR
116
+ WHERE phone_number = 5551234 -- MySQL: silent full scan via cast
117
+ WHERE phone_number = '5551234' -- seek (PostgreSQL errors instead)
118
+
119
+ -- Leading wildcard
120
+ WHERE sku LIKE '%XYZ' -- scan; use a reversed column or pg_trgm
121
+ WHERE sku LIKE 'XYZ%' -- seek
122
+ ```
123
+
124
+ The MySQL/PostgreSQL divergence on type mismatch is worth repeating: PostgreSQL
125
+ usually raises an error, MySQL silently casts every column value and turns a
126
+ 1 ms seek into a full scan with no warning in the logs.
127
+
128
+ ## Query anti-patterns and their rewrites
129
+
130
+ **`OR` across different columns** — no single B-tree can serve it; the engine
131
+ scans or does an index merge.
132
+
133
+ ```sql
134
+ SELECT id, full_name FROM employees WHERE department_id = 5 OR title = 'Director';
135
+ -- Rewrite: each branch uses its own index
136
+ SELECT id, full_name FROM employees WHERE department_id = 5
137
+ UNION
138
+ SELECT id, full_name FROM employees WHERE title = 'Director';
139
+ ```
140
+
141
+ **Offset pagination** — `LIMIT 20 OFFSET 500000` reads and discards 500,000 rows,
142
+ degrading linearly with page depth.
143
+
144
+ ```sql
145
+ -- Keyset (seek) pagination: O(log N) regardless of depth
146
+ SELECT id, title, created_at FROM posts
147
+ WHERE (created_at, id) < ('2025-02-14 10:30:00', 98214)
148
+ ORDER BY created_at DESC, id DESC
149
+ LIMIT 20;
150
+ ```
151
+ The composite tuple comparison is the part people omit; without the `id`
152
+ tie-breaker, rows sharing a timestamp are skipped or repeated.
153
+
154
+ **Correlated subquery in the SELECT list** — runs once per outer row.
155
+
156
+ ```sql
157
+ SELECT u.id, u.username,
158
+ (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
159
+ FROM users u;
160
+ -- Rewrite: one aggregation, joined once
161
+ SELECT u.id, u.username, COALESCE(o.order_count, 0) AS order_count
162
+ FROM users u
163
+ LEFT JOIN (SELECT user_id, COUNT(*) AS order_count FROM orders GROUP BY user_id) o
164
+ ON o.user_id = u.id;
165
+ ```
166
+
167
+ **`DISTINCT` hiding join fan-out** — materializes duplicates, then sorts them away.
168
+
169
+ ```sql
170
+ SELECT DISTINCT u.id, u.email FROM users u JOIN orders o ON u.id = o.user_id;
171
+ -- Rewrite: a semijoin stops at the first match per user
172
+ SELECT u.id, u.email FROM users u
173
+ WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);
174
+ ```
175
+
176
+ **Thousands of literals in `IN (...)`** — bloats parsing and wrecks selectivity
177
+ estimates. PostgreSQL: pass an array, `WHERE id = ANY($1::bigint[])`. MySQL/SQL
178
+ Server: load the IDs into a temporary table and join.
179
+
180
+ **`SELECT *`** — defeats covering indexes and ships columns nobody reads. List
181
+ the columns; it is what makes an index-only scan possible.
182
+
183
+ **`COUNT(*)` for pagination UI** — an exact count of a large filtered set is a
184
+ full scan every page load. Use an approximate count (`reltuples`, `EXPLAIN`
185
+ estimate) or a "load more" interaction.
186
+
187
+ ## Statistics
188
+
189
+ The optimizer plans from catalog samples: row counts, page counts, null
190
+ fractions, column histograms, most-common-values. After a bulk load or a large
191
+ delete they are stale, and a plan built for 10 rows runs against 500,000.
192
+
193
+ ```sql
194
+ ANALYZE users; -- PostgreSQL
195
+ ALTER TABLE users ALTER COLUMN status SET STATISTICS 500; -- more histogram detail
196
+ CREATE STATISTICS s_orders (dependencies) ON tenant_id, status FROM orders; -- correlated columns
197
+ ANALYZE TABLE users; -- MySQL
198
+ ```
199
+
200
+ Correlated columns are a classic misestimate source: the planner multiplies
201
+ independent selectivities, so `country='CH' AND city='Zurich'` is estimated far
202
+ too low. Extended statistics (PostgreSQL) fix exactly this.
203
+
204
+ ## Memory and spills
205
+
206
+ Sorts, hash tables and grouping need working memory. PostgreSQL's `work_mem` is
207
+ **per operation, per connection** — a query with four joins and two sorts can
208
+ allocate it six times over. MySQL uses `sort_buffer_size` and `join_buffer_size`.
209
+
210
+ In a plan, spills look like:
211
+
212
+ ```
213
+ Sort Method: external merge Disk: 4216kB
214
+ Buckets: 1024 Batches: 8 Memory Usage: …
215
+ ```
216
+
217
+ Raise it for the one statement, not globally:
218
+
219
+ ```sql
220
+ BEGIN;
221
+ SET LOCAL work_mem = '64MB';
222
+ SELECT * FROM large_table ORDER BY unindexed_column;
223
+ COMMIT;
224
+ ```
225
+
226
+ Better still, remove the sort: an index in the required order streams rows with
227
+ no sort node at all.
228
+
229
+ ## Parameter sniffing and plan regressions
230
+
231
+ Prepared statements cache a plan built from the first parameter values. If that
232
+ first value matched 2 rows, the cached Nested Loop will be reused for the value
233
+ matching 500,000 rows.
234
+
235
+ - PostgreSQL: `SET plan_cache_mode = force_custom_plan;` (session or role).
236
+ - SQL Server: `OPTION (RECOMPILE)` or `OPTIMIZE FOR`.
237
+ - MySQL: split the query into separate code paths by selectivity, or use hints.
238
+
239
+ ## The diagnostic loop
240
+
241
+ 1. **Capture**: `pg_stat_statements`, MySQL slow log / `performance_schema`,
242
+ `sys.dm_exec_query_stats`.
243
+ 2. **Prioritize by total impact** (`calls × mean_exec_time`), not worst single
244
+ call. A 50 ms query running 200k times an hour outweighs a 10 s nightly report.
245
+ 3. **Reproduce** with `EXPLAIN (ANALYZE, BUFFERS)` against production-like data
246
+ volume — a plan from a 1000-row dev table proves nothing.
247
+ 4. **Inspect**: unexpected sequential scans; actual vs estimated rows off by
248
+ orders of magnitude; sorts or hashes spilling to disk; buffer reads dominating
249
+ hits; `Rows Removed by Filter`.
250
+ 5. **Apply one fix** — statistics, an index, a rewrite, or a memory setting.
251
+ 6. **Measure again** and report both the before and after numbers (time *and*
252
+ buffers). If the plan did not change shape, the fix was not the fix.