Database Indexing Explained: How to Speed Up Slow Queries
November 28, 2026 · 11 min read

Database indexing is the single most effective way to speed up slow queries, and one of the most misunderstood. An index is a separate data structure that lets the database find rows without reading the whole table, much like the index at the back of a book lets you jump to the right page instead of reading every chapter. Add the right index and a query that took seconds can finish in a millisecond. Add the wrong ones and you slow down every insert and update while gaining nothing.
When a web page or API endpoint is slow, the cause is very often a query reading far more data than it needs, so understanding indexes pays off whichever database you use. This guide explains how indexes work, shows a tested PostgreSQL example where you can watch the query plan change as indexes are added, covers the main index types in PostgreSQL and MySQL, and ends with a practical checklist. The principles apply equally to SQL Server, SQLite and most other relational databases.
How a Database Index Works
Without an index, the database answers WHERE customer_id = 42 by reading every row and checking each one, which is called a sequential or full table scan. That is fine for a few thousand rows and painful for millions. Most indexes are B-trees: balanced, sorted tree structures in which each step narrows the search, so finding one value among a hundred million takes only a handful of page reads. Each index entry stores the indexed values and a pointer to the matching row.
Indexes are not free. Every insert, update or delete must also update each index on the table, indexes take disk space and memory, and the query planner must consider them when choosing a plan. The goal is not "index everything" but "index what your important queries actually filter, join and sort on".
Watch an Index Change a Query Plan
The best way to learn indexing is to read query plans. This script creates a table of 200,000 orders, then runs the same query, the ten most recent orders for one customer, with no index, with a composite index and with a covering index, printing PostgreSQL's plan each time. It runs real PostgreSQL 19 inside Node.js through PGlite, so you can try it without installing a database server:
// index-demo.mjs: watch PostgreSQL's query plan change as indexes are added
import { PGlite } from "@electric-sql/pglite";
const db = new PGlite();
await db.exec(`
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
total numeric(10, 2) NOT NULL,
created_at timestamptz NOT NULL
);
-- 200,000 orders spread evenly across 5,000 customers
INSERT INTO orders (customer_id, status, total, created_at)
SELECT g % 5000,
(ARRAY['paid', 'shipped', 'refunded'])[1 + g % 3],
(g % 20000) / 100.0,
timestamptz '2026-01-01' + g * interval '2 minutes'
FROM generate_series(1, 200000) AS g;
ANALYZE orders;
`);
const QUERY = `SELECT id, total, created_at FROM orders
WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10`;
async function plan(label) {
const res = await db.query(`EXPLAIN (ANALYZE, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY OFF) ${QUERY}`);
console.log(`-- ${label}`);
for (const row of res.rows) console.log(row["QUERY PLAN"]);
}
await plan("no index: every row is read");
await db.exec("CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at DESC)");
await plan("composite index: jump straight to customer 42, already sorted");
await db.exec(`DROP INDEX idx_orders_customer_created;
CREATE INDEX idx_orders_covering ON orders (customer_id, created_at DESC) INCLUDE (id, total)`);
await db.exec("VACUUM ANALYZE orders"); // updates the visibility map so index-only scans can skip the table
await plan("covering index: answered from the index alone");
Running it prints:
-- no index: every row is read
Limit (actual rows=10.00 loops=1)
-> Sort (actual rows=10.00 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 26kB
-> Seq Scan on orders (actual rows=40.00 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 199960
-- composite index: jump straight to customer 42, already sorted
Limit (actual rows=10.00 loops=1)
-> Index Scan using idx_orders_customer_created on orders (actual rows=10.00 loops=1)
Index Cond: (customer_id = 42)
Index Searches: 1
-- covering index: answered from the index alone
Limit (actual rows=10.00 loops=1)
-> Index Only Scan using idx_orders_covering on orders (actual rows=10.00 loops=1)
Index Cond: (customer_id = 42)
Heap Fetches: 0
Index Searches: 1
Read the plans from the inside out. Without an index, PostgreSQL performs a sequential scan, reads all 200,000 rows, throws away 199,960 of them and then sorts the remaining 40 to find the newest ten. With a composite index on (customer_id, created_at DESC), it jumps straight to customer 42's entries, which are already in date order, and stops after ten rows, so the sort disappears entirely. With a covering index that also includes id and total, the database answers from the index alone, and "Heap Fetches: 0" confirms it never touched the table. "Index Searches: 1" is a recent addition to PostgreSQL's output that shows how many times the index was descended.
Types of Indexes You Should Know
- B-tree: the default in PostgreSQL and MySQL, for equality, ranges, sorting and prefix searches.
- Unique indexes: enforce that values such as email addresses are never duplicated, and speed up lookups at the same time.
- Composite indexes: cover several columns in a chosen order, as in the example above.
- Covering indexes: include extra columns so queries can skip the table; PostgreSQL uses
INCLUDE, and in MySQL's InnoDB every secondary index already contains the primary key. - Partial indexes (PostgreSQL): index only rows matching a condition, such as
WHERE status = 'pending', keeping the index small. - Expression or functional indexes: index the result of an expression, such as
lower(email), so case-insensitive searches can use it. - GIN indexes (PostgreSQL): for JSONB documents, arrays and full-text search; MySQL offers FULLTEXT and multi-valued indexes for JSON arrays.
- GiST, SP-GiST and spatial indexes: for geographic data, ranges and nearest-neighbour searches.
- BRIN indexes (PostgreSQL): tiny indexes for huge, naturally ordered tables such as time-series logs.
- Vector indexes such as HNSW: approximate nearest-neighbour search over AI embeddings, explained in our guide to vector databases.
The official PostgreSQL index documentation and MySQL optimisation guide describe each type in detail.
Composite Indexes and Column Order
Column order in a composite index matters a great deal. A B-tree index on (customer_id, created_at) is sorted by customer first and date second, like a phone book sorted by surname then first name. It serves queries that filter on customer_id, or on both columns, very well. A query that filters only on created_at traditionally cannot use it efficiently, just as a phone book sorted by surname cannot quickly find everyone named Sarah. A good rule of thumb is to put columns tested for equality first, then columns used for ranges or sorting.
Modern databases soften this rule with skip scans. MySQL has supported them since version 8.0.13, and PostgreSQL added them in version 18, so a multicolumn index can still help when the leading column has few distinct values. Treat skip scans as a bonus, not a design strategy: if an important query filters on the second column alone, give it its own index.
How to Find Queries That Need an Index
- Collect evidence. In PostgreSQL, enable the pg_stat_statements extension to see which queries consume the most total time. In MySQL, turn on the slow query log.
- Read the plan. Run
EXPLAIN ANALYZEon the worst queries and look for sequential scans on large tables, large "rows removed by filter" counts and expensive sorts. - Index for the query, not the column. Look at the whole
WHERE,JOINandORDER BYclauses together. - Measure again after adding the index, and check that write performance is still acceptable.
In MySQL the same workflow looks like this:
-- MySQL 8.4 / 9.7: log slow queries, add the index, then check the plan
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.5; -- log anything slower than half a second
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC, total); -- InnoDB adds the primary key (id) automatically
EXPLAIN ANALYZE
SELECT id, total, created_at FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;
Watch out for ORMs, which can hide inefficient patterns such as the N+1 problem, where loading a list triggers one extra query per row. Logging the SQL your application sends during development reveals these quickly, and application monitoring tools highlight them in production; see our guide to observability vs monitoring.
When Indexes Hurt
- Write-heavy tables: every extra index slows inserts and updates, so tables that receive constant writes deserve fewer, carefully chosen indexes.
- Unused and duplicate indexes: PostgreSQL's
pg_stat_user_indexesview and MySQL'ssys.schema_unused_indexesshow indexes that are never read. An index on(a)is usually redundant if(a, b)exists. - Low-selectivity columns: an index on a true or false flag rarely helps unless you use a partial index for the rare value.
- Locking during creation: building an index on a large live table can block writes. Use
CREATE INDEX CONCURRENTLYin PostgreSQL, and check that MySQL performs the change as online DDL. - Functions on indexed columns:
WHERE date(created_at) = '2026-11-27'cannot use a plain index oncreated_at; rewrite it as a range or create an expression index.
A Practical Database Indexing Checklist
- Give every table a primary key, and index foreign keys that you join or filter on.
- Add unique indexes for values that must be unique, such as emails and external IDs.
- Index the columns in the
WHEREandORDER BYclauses of your most frequent and slowest queries. - Order composite index columns with equality filters first, then ranges and sorts.
- Use covering, partial and expression indexes for hot paths.
- Review unused indexes every quarter and drop the ones that cost more than they give.
- Keep statistics fresh, since the planner relies on them; autovacuum and analyse jobs handle this in PostgreSQL.
- Test with production-sized data, because a plan on 1,000 rows tells you little about 10 million.
Beyond Indexes
Database indexing fixes most slow queries, but not all. Repeated reads of the same data are better served by a cache, as explained in our guide to Redis caching. Reporting queries over huge tables may need summary tables, partitioning or a read replica. Plans that suddenly change after a statistics update can now be pinned with PostgreSQL 19's new plan advice tools, according to the release announcement. And sometimes the fix is in the data model itself; our guides to SQL vs NoSQL and PostgreSQL vs MySQL cover those choices. For a front-end view of performance, see our guide on how to make a website load faster. The site Use The Index, Luke is an excellent free resource if you want to go deeper.
Frequently Asked Questions
What is database indexing?
Database indexing means creating data structures, usually B-trees, that let the database find rows matching a condition without scanning the whole table, much like a book's index lets you find a topic without reading every page.
Do indexes slow down inserts and updates?
Yes, a little. Each index must be updated when rows change, so tables with many indexes write more slowly. The read speed gained is usually far larger, but avoid indexes that queries never use.
How many indexes should a table have?
There is no fixed number. Most tables need a primary key, indexes on frequently filtered foreign keys and a few composite indexes for key queries. Write-heavy tables should have fewer.
Should I index every foreign key?
Usually yes, if you join on it, filter by it or delete parent rows. PostgreSQL does not create these indexes automatically, while MySQL's InnoDB requires an index on foreign key columns and creates one if missing.
What is the difference between clustered and non-clustered indexes?
A clustered index determines the physical order of rows in the table, as InnoDB does with the primary key. A non-clustered index is a separate structure that points to the rows. PostgreSQL tables are heaps, so all its indexes are non-clustered.
Why is my query not using my index?
Common reasons are a function or type cast on the indexed column, the wrong column order in a composite index, outdated statistics, or the planner correctly judging that reading most of the table is faster. Check with EXPLAIN ANALYZE.
Make Your Application Fast Again
We profile slow applications, tune queries and indexes in PostgreSQL and MySQL, and add caching where it helps most. Contact our team for a database performance review.