Back to journalNotes from the craft

Database

What Is Database Indexing?

How database indexes reduce search work, which queries can benefit, and what indexes cost to maintain.

Nyi Nyi Zin

Software developer

What Is Database Indexing?
On this page

An application can feel fast when it has only a little data. As users and orders grow, queries that once returned quickly may start making people wait.

There are many reasons for slow queries. A missing index is one of them.

Think of a book’s index

Imagine finding a topic in a book with hundreds of pages. Looking up its page number in the index is quicker than reading every page.

A database index works in a similar way. It stores selected column values and information that helps locate the corresponding rows in a separate structure. This can reduce the amount of data a query needs to examine.

Example: finding a user by email

Suppose a table contains 100,000 users and you want to find one email address. Without a suitable index, the database may need to examine rows one by one. Reading through the table this way is called a full table scan.

If the email column has a suitable index and the database chooses to use it, the matching user can be located without scanning every row.

Having an index does not make every query faster. The search conditions and the number of rows returned also matter.

Which columns might need an index?

  • Columns frequently filtered with WHERE
  • Columns used to look up matching records in JOIN operations
  • Columns frequently used in ORDER BY

For values that must be unique, such as email addresses or usernames, you can also use a UNIQUE constraint or a unique index.

This list does not mean every such column should be indexed. Choose indexes based on the queries your application actually runs. Some queries benefit more from an index covering several columns than from an index on just one.

What does an index cost?

When a book’s content changes, its index may need updating too. Similarly, a database must maintain the relevant indexes when its data changes.

  • INSERT, UPDATE, and DELETE operations may involve extra work.
  • Indexes require additional storage.
  • Unnecessary indexes can increase maintenance costs without helping your searches.

How do you check whether an index helps?

Inspect the query with EXPLAIN. It shows how the database plans to find the data and whether it has chosen to use an index. Compare actual query timings as well.

An unused index is not always a problem. For a small table, or a query returning most of its rows, reading the table directly may be cheaper.

The purpose of an index is to reduce the work needed to find the data you want. Identify common and slow queries, add appropriate indexes, and measure the result afterward.

Database

Written by

Nyi Nyi Zin

I build for the web, mobile, and everything behind the scenes. This is where I share what I learn along the way.

More about me