Dataindexsecondary indexcomposite indexselectivity

Database index

Definition

A database index maps column values to the locations of matching rows, so queries filtering or sorting on those columns can seek instead of scan.

In practice

Without an index, a query reads every row and its cost grows with the table. An index, usually a B-tree, turns that into a few page reads without changing the query. Composite indexes serve a filter and a sort together when the columns are in the right order: equality filters first, then range or sort columns.

Every index must be updated on every write and takes memory and disk, so unused indexes are pure cost. Indexes only help selective filters; if a condition matches a large share of rows, the planner rightly scans anyway. Design indexes from real slow queries and confirm with EXPLAIN that they are used.

Example

SELECT * FROM orders WHERE customer_id = 42 scans 20 million rows in 3 s; after CREATE INDEX ON orders (customer_id) it reads a few pages and returns in under 1 ms.