MΓ³dulo 16 Β· Query Performance β LecciΓ³n 3 de 4 Β· ~11 min
EXPLAIN & Indexes
Reading EXPLAIN: seq scan vs. index scan
.includes fixed query COUNT. This lesson is about query COST β how expensive each individual query is once it hits the database. EXPLAIN (prefix any query with it in bin/rails dbconsole or wrap it with ActiveRecord::Base.connection.explain) shows you the plan the database actually ran:
- Seq Scan (sequential scan / full table scan): the database reads every row, checking each one against your
WHERE. Fine for a tiny table; ruinous for a bookings table with a million rows and a request that only wants 20 of them.
- Index Scan: the database uses an index β a separate, sorted structure β to jump straight to matching rows without touching the rest of the table. This is what you're aiming for on any column that shows up in a
WHEREorORDER BYon a large table.
The bookings table already has single-column indexes on user_id, walker_id, dog_id, and status β Rails added those automatically from t.references and the migration's index: true. The gap: index's real query filters user_id AND (optionally) status, then sorts by starts_at β three columns, one query, and no SINGLE index covers all three together.