🎓 A1Learner
🔍

Home / Blog / Databases / SQL

How Database Indexes Work, in Plain Words

Databases · SQL · 7 min read

A plain-words explanation of database indexes: what they store, how lookups use them, what they cost, and which columns are worth indexing.

A Shoebox Full of Slips

A small shop keeps every sale slip in a box, in the order the sales happened. To find all sales for one customer, the shopkeeper must read through the box slip by slip until the end. That works when the box is small. It grows tedious as the box fills, because every search costs a full pass through everything stored so far.

A database table without an index works the same way. A table stores records in rows. Each row is one record. Without an index, answering a question about one column means checking every row, a full table scan. An index is a separate structure the database builds and maintains beside the table, purely to make finding rows faster. It does not change the table's rows. It gives the database a quicker route to them.

SELECT * FROM sales WHERE customer_id = 42;
Without an index on customer_id, this question means checking every row.

What an Index Stores

An index stores a sorted list of values from one or more columns, together with a pointer for each value. A pointer is a reference that tells the database where the full row lives in the table. Think of it as a sorted list of customer numbers, each with a note saying which slip in the box it belongs to. The list itself is sorted, so a value can be found without reading the whole list from the start.

The database keeps this list up to date on its own. When a row is added, changed, or removed, the database updates every index on that table as well. That automatic upkeep is part of the deal, and it is also the source of the costs described later. A writer creates an index once with a statement like the one below, and the database then maintains it.

One common misunderstanding is worth clearing up early. An index is not a copy of the table. It holds only the indexed columns plus pointers, so it is smaller than the table, but it still takes storage space. Several indexes on one table can add up to a noticeable amount of extra storage.

CREATE INDEX idx_sales_customer ON sales(customer_id);
Creating an index on one column of the sales table.

How a Lookup Uses the Index

Most databases store an index as a B-tree. A B-tree is a balanced tree, meaning a branching structure whose paths stay roughly equal in length, so no value sits much deeper than any other. The top of the tree holds ranges of values, and each branch narrows the range until the search reaches the matching entries at the bottom. Because the entries are sorted, each step discards a large share of the values that cannot match, instead of checking them one by one.

A lookup then runs in two stages. First the database walks the tree to find the matching entries in the index. Then it follows their pointers to fetch the full rows from the table. When only a few rows match, this is far less work than scanning the whole table. When a great many rows match, the second stage dominates, and the database may reasonably decide that scanning the table directly is cheaper than chasing a long trail of pointers.

That decision is made by the query planner, an internal part of the database that picks a plan for each query. The writer asks for rows. The planner decides whether an index, a scan, or some other route answers fastest, based on the query and on statistics about the data. Creating an index is therefore a suggestion the database can use, not an order it must follow.

EXPLAIN SELECT * FROM sales WHERE customer_id = 42;
EXPLAIN shows the plan the database chose, including whether it used an index.

What an Index Speeds Up, and What It Does Not

An index helps most when a query filters, joins, or sorts on the indexed column and matches a modest share of the rows. Filtering means narrowing rows with a condition, such as one customer number. Joining means pairing rows from two tables on a shared value, and an index on that value lets the database find partners quickly instead of scanning. Sorting also benefits, because the index already holds values in order, so the database may read them in that order rather than sorting from scratch.

An index helps far less when the query matches a large share of the table. Finding half of all sales by a common status value, for example, still requires fetching half the rows, and chasing pointers row by row can cost more than a straight scan. The same applies to a column with very few distinct values, such as a yes-or-no flag. Splitting rows into two huge groups narrows almost nothing, so the planner often ignores such an index entirely.

An index can also be skipped for a subtler reason: the query changes the column before comparing it. Wrapping an indexed column in a function, or searching with a leading wildcard such as a pattern that starts with a percent sign, hides the stored order from the planner. The database cannot use the sorted list if the values it must compare are not the values stored in it. Comparing the column directly, or indexing the exact expression used, avoids this trap.

SELECT * FROM sales WHERE customer_id = 42 ORDER BY sale_date;
A query that filters and sorts: an index on customer_id helps the filter, and a suitable index can help the order too.

The Price of Every Index

Every index is paid for on every write. Inserting a row means adding an entry to each index on that table. Updating an indexed column means moving that entry to its new sorted position. Deleting a row means removing its entries. A table with many indexes therefore writes more slowly, because one row change becomes several pieces of maintenance work. Tables that are written constantly and read rarely are poor candidates for heavy indexing.

Storage is the second price. Each index holds its own sorted copy of its columns plus pointers, and that copy grows with the table. The third price is attention. Unused indexes still cost storage and write time while helping nobody, so they deserve periodic review. A database can usually report which indexes exist and, in many systems, whether they have been used, and dropping a dead index is a safe, reversible cleanup.

DROP INDEX idx_sales_customer;
Removing an index never deletes table rows; it only removes the lookup structure.

Choosing Columns Worth Indexing

Start from the queries you actually run, not from a wish list. Index columns that appear often in filters, join conditions, and sort orders, especially columns that pick out a small share of rows, such as a customer number or an order number. Primary keys, which are the columns that uniquely identify each row, are indexed automatically in most databases, so they need no extra work.

For several columns used together, one multi-column index can serve better than several single-column ones, but column order matters. Put first the column your queries filter on most often, because the database can only use the later columns efficiently when the earlier ones are also constrained. An index on customer number followed by sale date serves queries for one customer in date order well, but it helps a query filtered only by sale date much less.

Leave alone columns you rarely query, columns with only a handful of distinct values, and columns whose values change constantly if reads do not justify the upkeep. When a query stays slow after adding an index, check the plan before adding another. If the plan shows a full scan where an index was expected, look for a function wrapped around the column, a mismatched data type, or a match so broad that a scan is genuinely cheaper. Adding indexes blindly makes writes slower without fixing the read.

CREATE INDEX idx_sales_customer_date ON sales(customer_id, sale_date);
A multi-column index: customer first, because queries usually filter by customer first.

Questions readers ask

Why is my query still slow after I added an index?

The planner may have ignored it. Common reasons are a function wrapped around the indexed column, a search pattern with a leading wildcard, or a match so broad that a full scan is cheaper. Run EXPLAIN on the query to see which plan the database chose.

Do indexes slow down inserts and updates?

Yes. Every insert, update, or delete on a table must also update each of its indexes. The cost is small for one index and grows with each additional index.

Should I index every column in a table?

No. Index the columns your real queries filter, join, or sort on, and skip columns you rarely query or that hold only a few distinct values. Unused indexes cost storage and write time for no benefit.

What is a multi-column index, and why does column order matter?

A multi-column index sorts by several columns in a fixed order. Queries that constrain the first column can use the later columns efficiently, but queries that constrain only a later column usually cannot use the index well.