Databases

Database Indexes: How They Speed Up Queries

By ScaleVar Editorial Team · · 4 min read

A query that runs instantly on a small test database can crawl once the table holds millions of rows. Very often, the fix is a single line of SQL that creates an index. Yet indexes are also a common source of confusion: what are they, why do they help, and why not simply index everything?

This article explains the idea with a familiar comparison, then covers how to use indexes sensibly.

The Book Index Analogy

Imagine looking for a topic in a thick book with no index. You would have to read page after page until you found it. With an index at the back, you look up the word, find the page numbers and jump straight there.

A database index works the same way. Without one, the database must read every row in the table to find matches for your condition, a method called a full table scan. With an index on the relevant column, it can look up the value in a small, organized structure and go directly to the matching rows.

How an Index Is Built

Most relational databases implement indexes as a B-tree, a balanced tree structure. Values are kept in sorted order, and the tree is shallow and wide, so finding any value takes only a few steps even among millions of entries. Each entry points to the location of the actual row.

Because the values are sorted, a B-tree index helps with more than exact matches. It also speeds up:

  • Range conditions, such as dates between two values.
  • Sorting results by the indexed column.
  • Prefix searches, such as names starting with a given text.

Other index types exist for special jobs, including hash indexes for exact lookups, and specialized structures for full-text search, geographic data and arrays.

A Concrete Example

Suppose an orders table has millions of rows, and your application often runs this query.

SELECT * FROM orders WHERE customer_id = 4821;

Without an index on customer_id, the database examines every row. Creating one is simple.

CREATE INDEX idx_orders_customer_id ON orders (customer_id);

Now the database finds the matching entries in the tree and fetches only those rows. Most databases offer an EXPLAIN command that shows the plan chosen for a query, so you can confirm whether the index is used.

Primary keys and unique constraints already create indexes automatically in most systems.

Indexes Are Not Free

Every index has costs, which is why you should not add them blindly.

  • Slower writes. Each insert, update or delete must also update every affected index.
  • Extra storage. Indexes occupy disk space and memory, sometimes a lot.
  • Maintenance. Over time, indexes may need rebuilding or tuning.
  • Planner confusion. Too many overlapping indexes can make it harder for the database to choose well.

The trade is faster reads for slower writes. For read-heavy tables, that is usually a good deal. For tables that take constant heavy writes, be more selective.

Choosing What to Index

Base your decisions on how the data is actually queried.

  1. Columns in WHERE clauses that filter many rows down to few.
  2. Columns used in joins, particularly foreign keys.
  3. Columns used in ORDER BY for large result sets.
  4. Columns with high selectivity, meaning many distinct values. An index on a yes or no column rarely helps, since each value matches half the table.

Look for slow queries first. Database logs and monitoring tools can show which statements take the longest, and the query plan explains why.

Composite Indexes

An index can cover more than one column. A composite index on (customer_id, order_date) serves queries that filter on the customer, and queries that filter on the customer and a date range.

Column order matters. The index is sorted first by the first column, then by the second within it. It helps queries that use the leading column or columns, but generally not queries that filter only on the second column. Put the column you filter by most often, or with equality, first.

A composite index can also act as a covering index: if it includes every column the query needs, the database can answer from the index alone without touching the table.

Situations Where Indexes Get Ignored

Sometimes an index exists but the database does not use it.

  • Wrapping the column in a function, such as applying a lowercase function to the column, usually prevents plain index use unless a matching expression index exists.
  • A leading wildcard in a text search, like a pattern beginning with a percent sign, cannot use a normal B-tree.
  • Comparing values of mismatched types may force conversions.
  • On a very small table, a full scan can be quicker, so the planner skips the index.
  • If a condition matches a large share of rows, scanning may be cheaper than jumping around through an index.

Good Habits

  • Index in response to real, measured queries.
  • Remove unused indexes after confirming that nothing relies on them.
  • Test changes on realistic data volumes, since tiny test data hides problems.
  • Re-check query plans after major data growth or software upgrades.

Frequently Asked Questions

Should I index every column?

No. Each index slows down writes and uses storage. Index the columns that appear in frequent filters, joins and sorts, and leave the rest alone unless measurements show a need.

Why is my query still slow even with an index?

The database may be skipping the index because of a function on the column, a mismatched type, a very broad condition or a small table. Use the EXPLAIN command to see the actual plan and find out.

Does an index change my query results?

No. An index only affects how quickly the database finds rows. The results are the same with or without it, apart from the order in cases where you did not specify one.

Related reading