Indexes and reading query plans
Why a query is slow, how an index helps and how to check with EXPLAIN.
An index is a separate sorted structure (usually a B-tree) that lets the database find rows without reading the whole table. It speeds up reads and slows down writes a little, because every change must update the index too.
CREATE INDEX idx_orders_user_id ON orders (user_id);
CREATE UNIQUE INDEX idx_users_email ON users (email);Read the plan, do not guess
EXPLAIN shows how the database plans to run a query. EXPLAIN ANALYZE (PostgreSQL) really runs it and adds actual timings.
EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 42;- Seq Scan / full table scan: reads every row. Fine for small tables, a warning on big ones.
- Index Scan / Index Seek: uses an index to jump to the matching rows.
- Compare the estimated rows with the actual rows. A big gap means stale statistics, so run
ANALYZE.
Rules that decide whether an index is used
- A multi-column index
(a, b)helps filters onaor onaandb, but not onbalone (the leftmost prefix rule). - Wrapping the column in a function, as in
WHERE lower(email) = ..., usually stops a plain index from being used. Create an index on the expression instead. - Low-selectivity columns (like a yes/no flag) rarely benefit from an index.
- A leading wildcard
LIKE '%abc'cannot use a normal B-tree index.
CarefulDo not add an index for every column. Each one costs disk space and slows INSERT, UPDATE and DELETE. Add indexes for queries you have measured.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.