Database Indexing: How Indexes Speed Up Queries

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 and What is a 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
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
);
A Query Without an Index
Let’s find a customer by email, which a login page does on every sign-in:
SELECT id, name FROM customers WHERE email = 'user424242@example.com';
How does the database run this? Most databases let you ask with EXPLAIN (SQLite uses EXPLAIN QUERY PLAN, MySQL EXPLAIN, PostgreSQL EXPLAIN ANALYZE):
EXPLAIN QUERY PLAN
SELECT id, name FROM customers WHERE email = 'user424242@example.com';
-- SCAN customers
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:
EXPLAIN QUERY PLAN
SELECT id, name FROM customers WHERE email = 'user424242@example.com';
-- SEARCH customers USING INDEX idx_customers_email (email=?)
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:
[ root: ... m ... t ... ]
/ | \
[ a ... f ... l ] [ m ... p ... s ] [ t ... w ... z ]
/ | \ / | \ / | \
leaf pages: sorted email values, each with a pointer to its row
- 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, 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: 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:
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.email
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:
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 BY
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:
-- 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_date
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:
SELECT email FROM customers WHERE email = 'user5@example.com';
-- SEARCH customers USING COVERING INDEX idx_customers_email (email=?)
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:
SELECT id FROM customers WHERE lower(email) = 'user5@example.com';
-- SCAN customers USING COVERING INDEX idx_customers_email
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:
SELECT id FROM customers WHERE email LIKE '%@example.com';
-- SCAN customers USING COVERING INDEX idx_customers_email
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:
no indexes: 0.14 s
four indexes: 1.59 s (about 11 times slower)
So the goal is not “index everything”, but “index what your queries need”:
- Do index: columns used in
WHERE,JOIN ... ON(especially foreign keys likeorders.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_indexesand MySQL’ssys.schema_unused_indexescan 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 (SCANin SQLite,type: ALLin MySQL,Seq Scanin PostgreSQL) on a large table, and for an extra sort step. - Add an index on the columns in
WHERE, thenORDER BY, with equality columns first. - Run
EXPLAINagain 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
LIKEwith%.
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.


