Video in progress

What is an index and how does it speed up lookups?

An index is a separate sorted structure built from the column values (a B-tree by default in PostgreSQL) that points to where the row is. Without an index the database reads the whole table; with one it reaches the right spot in a few steps down the tree.

📖 Answer

Think of the alphabetical index at the back of a book: "Transaction — p. 145". You don't flip through the whole book.

-- no index: reads all 10M rows sequentially (Seq Scan)
SELECT * FROM users WHERE email = 'ali@mail.uz';

CREATE INDEX idx_users_email ON users(email);
-- now: reads 3-4 pages down the B-tree (Index Scan)

A B-tree keeps values in order, so it works not only for = but also for <, >, BETWEEN, ORDER BY and LIKE 'abc%' (with the C collation or text_pattern_ops).

An index isn't always used. If the condition returns a large part of the table (say WHERE active = true and 95% of rows are active), the planner decides a full table read is cheaper. You see this with EXPLAIN.

When you add an index to a big table in production, use CREATE INDEX CONCURRENTLY. A plain CREATE INDEX blocks writes to the table.