A database index helps the database find rows without reading the whole table. Think of a book index: to find every mention of “transactions,” you look up the word and jump to the listed pages. A database index does something similar with column values and rows.

## What happens during a lookup

Suppose you have a million orders and run this query:

```sql
SELECT *
FROM orders
WHERE customer_id = 42;
```

Without a usable index, the database may scan the table and check each row’s `customer_id`. You can give it another option:

```sql
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
```

A common index structure is a **B-tree**. Its entries are sorted by key, and its upper levels guide the database to the page where `42` would appear. The database then reads the adjacent entries for `42` and follows their row references to fetch the orders. If customer 42 has twelve orders, the database can locate those twelve without examining every customer’s orders.

The sorted order also helps with ranges. For `WHERE customer_id BETWEEN 40 AND 50`, the database can seek to `40` and read forward until it passes `50`.

## Why column order matters

An index can cover multiple columns:

```sql
CREATE INDEX orders_customer_date_idx
ON orders (customer_id, created_at);
```

Imagine sorting a spreadsheet by customer first and date second. Each customer’s orders form a group, and the dates are sorted **within** each group. That makes this index a good fit for:

```sql
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;
```

The database can jump to customer 42’s group and read the ten newest entries. For a query that asks for the newest orders across **all** customers, the dates are spread across those groups. An index starting with `created_at` fits that query better.

## Why the database sometimes scans anyway

If a query needs most of the table, reading table pages in sequence can be cheaper than walking the index and fetching rows scattered across many pages. The query planner estimates both costs and chooses a plan. You can use `EXPLAIN` to see what it chose.

Indexes also take up storage and add work when rows are inserted, deleted, or changed in ways that affect indexed values. A practical starting point is to pick a frequent query, look at its filters and sort order, and check whether an index lets the database read substantially less data.