2.2 KiB
2.2 KiB
Indexing — Derived Rules
Derives from
domains/data/first-principles.mdP5 (Indexing with Intent), P10 (Performance Awareness).
Index for Queries, Not Tables (P5)
- An index serves a query. No query, no index.
- The query plan is the spec.
EXPLAINis the test. An index that is not used is dead weight. - Index the columns you filter on (
WHERE), join on (JOIN), and sort on (ORDER BY).
Composite Indexes (P5, P10)
- Order matters:
INDEX(a, b)servesWHERE a = ? AND b = ?andWHERE a = ?, but NOTWHERE b = ?. - Put the most selective column first. Or the column used in every query. Depends on the workload.
- An index on every column is not a strategy. It is write amplification.
Unique Indexes (P3 Invariants in Schema)
- A uniqueness constraint is a unique index. Use it for invariants:
email,username. - Unique indexes enforce; application checks defend. Both belong.
- A partial unique index:
UNIQUE(email) WHERE deleted_at IS NULL— allows soft-deleted duplicates.
Covering Indexes (P10)
- An index that covers all columns of a query is an "index-only scan" — no table lookup.
- PostgreSQL:
INCLUDEclause. MySQL: all columns in the index. - Use for hot queries. Don't cover everything; index size matters.
Don't Over-Index (P10, core C8 Economy)
- Every index costs a write. The write budget is the index count.
- Indexes take disk and memory. A 1GB index on a 500MB table is a smell.
- Remove unused indexes.
pg_stat_user_indexesshows usage. An unused index is debt.
Migration and Indexes (P4 Migration Safety)
- Adding an index on a large table is expensive. Do it concurrently (
CREATE INDEX CONCURRENTLY). - An index migration that locks the table blocks writes. Plan for it.
- Build the index, then deploy the query that uses it. Not the reverse.
What Violates Indexing Discipline
| Violation | Principle |
|---|---|
| Index on every column | P10, C8 Economy |
| No index on a foreign key | P10 (join performance) |
WHERE b = ? with only INDEX(a, b) |
P5 (wrong order) |
| Index created without checking the query plan | P5 (no intent) |
CREATE INDEX (non-concurrent) on a 10M-row table in prod |
P4 Migration Safety |