---
title: "Database Indexing: How Indexes Speed Up Queries"
url: https://www.khanwaseem.com/blog/database/database-indexing
author: "khan Waseem"
published: 2026-11-26
updated: 2026-11-26
topics: ["Database", "Blog"]
description: "What a database index is, how B-tree indexes turn a full table scan into a fast search, how to create single-column, composite, unique and covering indexes, how to read a query plan, and when an index slows things down…"
---

# Database Indexing: How Indexes Speed Up Queries

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [The Example Tables](#the-example-tables)
- [A Query Without an Index](#a-query-without-an-index)
- [Creating an Index](#creating-an-index)
- [How an Index Works: The B-Tree](#how-an-index-works-the-b-tree)
- [Types of Indexes](#types-of-indexes)[1. Primary Key Index:](#1-primary-key-index)
- [2. Unique Index:](#2-unique-index)
- [3. Composite (Multi-Column) Index:](#3-composite-multi-column-index)
- [4. Covering Index:](#4-covering-index)

- [When the Index Can’t Be Used](#when-the-index-cant-be-used)[1. A function on the column:](#1-a-function-on-the-column)
- [2. A leading wildcard:](#2-a-leading-wildcard)
- [3. Skipping the first column of a composite index:](#3-skipping-the-first-column-of-a-composite-index)
- [4. Very common values:](#4-very-common-values)

- [The Cost of Indexes](#the-cost-of-indexes)
- [A Practical Checklist for a Slow Query](#a-practical-checklist-for-a-slow-query)
- [Conclusion:](#conclusion)

## Introduction:

Imagine looking for the word “recursion” in a 900-page programming book that has **no index**. You would have to read every page from the beginning. With the index at the back, you look up “recursion”, see “page 412”, and jump straight there.

A **database index** works the same way. Without one, the database has to read **every row** of a table to find the rows you asked for. This is called a **full table scan**. With the right index, it can jump almost directly to the matching rows, even in a table with millions of rows.

Indexes are the single most effective way to speed up slow queries, and one of the most common topics in backend and database interviews. In this lesson we will see how indexes work, how to create the different kinds, how to check whether a query uses one, and when indexes actually hurt performance. It builds on [What is SQL](https://blog.khanwaseem.com/what-is-sql/) and [What is a Database](https://blog.khanwaseem.com/what-is-database/).

All the examples below were run in **SQLite** on a test table of **500,000 customers** and **1,000,000 orders**. The same ideas apply to MySQL, PostgreSQL and SQL Server.

## The Example Tables

```javascript
CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  email TEXT,
  name TEXT,
  city TEXT,
  created_at TEXT
);

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  status TEXT,        -- 'pending', 'paid', 'shipped' or 'cancelled'
  total REAL,
  created_at TEXT
);Code language: JavaScript (javascript)
```

## A Query Without an Index

Let’s find a customer by email, which a login page does on every sign-in:

```javascript
SELECT id, name FROM customers WHERE email = 'user424242@example.com';Code language: JavaScript (javascript)
```

How does the database run this? Most databases let you ask with **`EXPLAIN`** (SQLite uses `EXPLAIN QUERY PLAN`, MySQL `EXPLAIN`, PostgreSQL `EXPLAIN ANALYZE`):

```javascript
EXPLAIN QUERY PLAN
SELECT id, name FROM customers WHERE email = 'user424242@example.com';

-- SCAN customersCode language: JavaScript (javascript)
```

**`SCAN customers`** means it reads the whole table, all 500,000 rows, to find one customer. On our test machine this took about **20 milliseconds** per query. That sounds small, but a busy login page might run it hundreds of times a second, and the time grows with every new customer.

## Creating an Index

```
CREATE INDEX idx_customers_email ON customers(email);
```

Now the same question gives a very different plan:

```javascript
EXPLAIN QUERY PLAN
SELECT id, name FROM customers WHERE email = 'user424242@example.com';

-- SEARCH customers USING INDEX idx_customers_email (email=?)Code language: JavaScript (javascript)
```

**`SEARCH ... USING INDEX`** means the database looks the email up in the index and jumps to the matching row. The query time dropped from about **20 ms to 0.005 ms**, thousands of times faster. And unlike the scan, it will stay fast as the table grows to 5 million or 50 million rows.

## How an Index Works: The B-Tree

Most database indexes are **B-trees** (balanced trees). You can picture a B-tree as a sorted, multi-level table of contents:

```javascript
                    [ root:  ...  m  ...  t  ... ]
                   /               |               \
       [ a ... f ... l ]     [ m ... p ... s ]     [ t ... w ... z ]
          /    |    \          /    |    \           /    |    \
       leaf pages: sorted email values, each with a pointer to its rowCode language: JavaScript (javascript)
```

- The index stores the indexed column’s values **in sorted order**, each with a pointer to the full row in the table.

- To find a value, the database starts at the root and follows one branch per level, like a [binary search](https://blog.khanwaseem.com/searching-algorithms/), but each node has hundreds of children instead of two.

- Because each level splits the data hundreds of ways, even a billion rows need only about **3 to 5 levels**. That is why a lookup costs **O(log n)** instead of the **O(n)** of a full scan.

Because the values are sorted, a B-tree index also speeds up **range** queries (`BETWEEN`, `<`, `>`), **`ORDER BY`** on the indexed column, and prefix searches like `LIKE 'abc%'`.

Some databases also offer **hash indexes**, which work like a [hash table](https://blog.khanwaseem.com/hash-table-data-structure/): very fast for exact matches (`=`), but useless for ranges and sorting. B-trees are the default because they handle both.

## Types of Indexes

### 1. Primary Key Index:

Every table’s primary key is indexed automatically. That’s why `WHERE id = 42` is always fast. In MySQL’s InnoDB engine the table itself is stored in primary-key order (a **clustered index**).

### 2. Unique Index:

A unique index speeds up lookups **and** guarantees that no two rows have the same value, which is perfect for emails and usernames:

```javascript
CREATE UNIQUE INDEX idx_customers_email_unique ON customers(email);

INSERT INTO customers (email, name) VALUES ('user5@example.com', 'Copy');
-- IntegrityError: UNIQUE constraint failed: customers.emailCode language: JavaScript (javascript)
```

Adding a `UNIQUE` constraint to a column creates such an index for you.

### 3. Composite (Multi-Column) Index:

An index can cover several columns. Take a common query on a “My orders” page:

```php
SELECT id, total FROM orders
WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC;

-- Without an index:
-- SCAN orders | USE TEMP B-TREE FOR ORDER BYCode language: PHP (php)
```

The database scans a million orders and then sorts the results in a temporary structure. One composite index fixes both problems:

```
CREATE INDEX idx_orders_customer_status_date
  ON orders(customer_id, status, created_at);

-- SEARCH orders USING INDEX idx_orders_customer_status_date (customer_id=? AND status=?)
```

The index is sorted by `customer_id`, then by `status` within each customer, then by `created_at`. So the matching rows are already next to each other **and** already in date order. The temporary sort disappears from the plan.

**The order of columns matters.** A composite index works like a phone book sorted by last name, then first name: you can quickly find everyone named “Khan”, but not everyone whose first name is “Sara”. This is the **leftmost prefix rule**:

```php
-- Uses the index: customer_id is the first column
SELECT id FROM orders WHERE customer_id = 42;
-- SEARCH orders USING COVERING INDEX idx_orders_customer_status_date (customer_id=?)

-- Can't search the index: status is not the first column
SELECT id FROM orders WHERE status = 'paid';
-- SCAN orders USING COVERING INDEX idx_orders_customer_status_dateCode language: PHP (php)
```

The second query still reads every entry (a `SCAN`), just from the smaller index instead of the table. A good rule of thumb: put columns compared with **`=`** first, then the column used for ranges or sorting.

### 4. Covering Index:

Normally the database finds the row in the index and then fetches the rest of the row from the table. If the index already contains **every column the query needs**, that second step is skipped. This is called a **covering index**:

```javascript
SELECT email FROM customers WHERE email = 'user5@example.com';
-- SEARCH customers USING COVERING INDEX idx_customers_email (email=?)Code language: JavaScript (javascript)
```

You can design covering indexes for your most important queries by adding the selected columns at the end of a composite index (PostgreSQL and SQL Server also have an `INCLUDE` clause for this).

## When the Index Can’t Be Used

An index only helps if the database can search it. These common patterns force a scan even when an index exists:

### 1. A function on the column:

```javascript
SELECT id FROM customers WHERE lower(email) = 'user5@example.com';
-- SCAN customers USING COVERING INDEX idx_customers_emailCode language: JavaScript (javascript)
```

The index stores `email`, not `lower(email)`, so the database must check every entry. Store emails in lower case to begin with, or create an **expression index**: `CREATE INDEX idx_email_lower ON customers(lower(email));` (supported by SQLite, PostgreSQL and MySQL 8).

### 2. A leading wildcard:

```javascript
SELECT id FROM customers WHERE email LIKE '%@example.com';
-- SCAN customers USING COVERING INDEX idx_customers_emailCode language: JavaScript (javascript)
```

A sorted list can find everything that **starts with** “user5” but not everything that **ends with** “@example.com”. For searching inside text, use a full-text index instead.

### 3. Skipping the first column of a composite index:

As we saw above with `WHERE status = 'paid'`.

### 4. Very common values:

If a query matches a large part of the table (for example `WHERE status = 'paid'` when half of all orders are paid), the query planner may decide that scanning the table is cheaper than jumping back and forth through the index. Indexes help most on **selective** columns, where each value matches few rows.

## The Cost of Indexes

Indexes are not free. Each index is a separate sorted structure that must be updated on every `INSERT`, `UPDATE` and `DELETE`, and it takes up disk space and memory.

We inserted the same 200,000 rows into two tables, one with no indexes and one with an index on each of its four columns:

```css
no indexes:    0.14 s
four indexes:  1.59 s   (about 11 times slower)Code language: CSS (css)
```

So the goal is not “index everything”, but “index what your queries need”:

- **Do index:** columns used in `WHERE`, `JOIN ... ON` (especially foreign keys like `orders.customer_id`), `ORDER BY`, and columns that must be unique.

- **Think twice about:** tables that are written much more often than read (such as logs), columns with very few distinct values (like a true/false flag), and tiny tables, where a scan is already fast.

- **Remove** indexes that no query uses. PostgreSQL’s `pg_stat_user_indexes` and MySQL’s `sys.schema_unused_indexes` can show you which ones they are.

## A Practical Checklist for a Slow Query

- Find the slow query (from your database’s slow query log or your app’s monitoring).

- Run it with `EXPLAIN`. Look for a full scan (`SCAN` in SQLite, `type: ALL` in MySQL, `Seq Scan` in PostgreSQL) on a large table, and for an extra sort step.

- Add an index on the columns in `WHERE`, then `ORDER BY`, with equality columns first.

- Run `EXPLAIN` again to confirm the index is used, and measure the time.

- Make sure the query doesn’t wrap the column in a function or start a `LIKE` with `%`.

## Conclusion:

A database index is a sorted structure, usually a B-tree, that lets the database find rows in O(log n) steps instead of scanning the whole table. On our 500,000-row table, one index made an email lookup thousands of times faster. Use unique indexes to enforce uniqueness, composite indexes for queries that filter on several columns (remembering the leftmost prefix rule), and covering indexes for your hottest queries. Always check with `EXPLAIN`, avoid functions and leading wildcards on indexed columns, and remember that every index slows down writes, so add the ones your queries need and no more.

In the next database lesson we will look at **SQL joins**, and you will see why indexing foreign key columns matters so much.

### Related posts:

[CSS – Table](https://blog.khanwaseem.com/css-table/)
[What is MYSQL Database?](https://blog.khanwaseem.com/sql/)
[HTML – Tables](https://blog.khanwaseem.com/html-tables/)
[MongoDB: Unveiling the Power of NoSQL Database](https://blog.khanwaseem.com/mongodb-unveiling-the-power-of-nosql-database/)

Powered by [YARPP](https://yarpp.com).
