The full answer
An index is a separate, sorted structure (usually a B-tree) that maps column values to the rows that contain them, so the database can find matching rows without reading the whole table. Each index speeds up the reads that can use it and slows down every write, because each INSERT, UPDATE and DELETE must update it too.
How it works
Like the index at the back of a book: to find customer_id = 42, the database walks a small tree to the entries for 42 and follows them to the rows.
CREATE INDEX idx_orders_customer ON orders (customer_id);
Trade-offs
| Many indexes | Few indexes | |
|---|---|---|
| Reads | More queries find an index that fits | More full scans |
| Writes | Slower: every index is updated | Faster |
| Storage and memory | More disk, and indexes compete for cache | Less |
| Planning | More options for the optimizer, occasionally a wrong choice | Simpler |
| Maintenance | More to monitor; unused indexes still cost writes | Less |
The right number depends on the workload: a reporting database that is loaded nightly can carry many indexes; a table taking thousands of inserts a second should carry few.
Kinds of index worth knowing
- B-tree: the default; handles equality, ranges, sorting and prefix
LIKE 'abc%'. - Composite (multicolumn): one index on
(customer_id, order_date)serves filters oncustomer_idalone or on both, but not onorder_datealone. Put equality columns first. - Covering: includes extra columns (
INCLUDEin PostgreSQL and SQL Server) so the query never touches the table. - Partial or filtered: indexes only rows matching a condition, such as
WHERE status = 'open', which keeps it small. - Hash: equality only.
- Full-text, GIN and GiST (PostgreSQL) for text search, arrays, JSON and ranges.
- Clustered: in SQL Server and MySQL InnoDB, the table itself is stored in the order of the clustered index (the primary key in InnoDB).
Good practice
- Index for the queries you actually run: check plans with
EXPLAIN. - Find unused indexes (
pg_stat_user_indexesin PostgreSQL,sys.dm_db_index_usage_statsin SQL Server) and drop them. - Avoid indexing columns with very few distinct values on their own, such as a boolean, unless the index is partial.
- Rebuild only when monitoring shows bloat or fragmentation hurts; routine rebuilds are rarely needed on modern systems.
Last updated 16 October 2026
Sources