Part 07 / Topic 5 of 6
Indexes for the queries users run
Index for the customer's actual queries, and let the database tell you what it is doing rather than guessing:
CREATE INDEX idx_shipments_customer ON shipments (customer, status);
EXPLAIN QUERY PLAN SELECT * FROM shipments WHERE customer = 'Bolt Retail' AND status = 'delayed';
-- SEARCH shipments USING INDEX idx_shipments_customer (customer=? AND status=?)
(EXPLAIN QUERY PLAN is SQLite's spelling; Postgres says EXPLAIN ANALYZE.) A SEARCH ... USING INDEX (or Postgres's Index Scan) means the index is used; a SCAN on a large table under a user-facing query is your cue. Two cautions from the field: indexes cost write time — a sync job hammering upserts pays for every index on the table — and an index on a column nobody filters by is pure cost. Add indexes when a real query plan shows the need, not preemptively.
Done here? The practice set for Part 7 — 4 exercises with solutions — is on the part page.