Skip to content

No. 46Database8 min read2,195 words

Database indexing for developers: a practical Postgres guide

Database indexing for app developers: how indexes work, reading EXPLAIN ANALYZE, composite index column order, partial and covering indexes, and the costs.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01An index is a separate sorted structure, usually a B-tree, that lets the database find matching rows without scanning the whole table; reads get faster, writes get slightly slower and storage grows.
  2. 02Use EXPLAIN (ANALYZE, BUFFERS) before and after adding an index: a Seq Scan with a large Rows Removed by Filter count on a big table is the classic sign of a missing index.
  3. 03In a composite index, put equality columns first and the range or sort column last; an index on (customer_id, created_at) serves filters on customer_id but not on created_at alone.
  4. 04Postgres does not index foreign key columns automatically, so add an index on every foreign key you filter or join on.
  5. 05On live production tables, build indexes with CREATE INDEX CONCURRENTLY, and periodically drop indexes that pg_stat_user_indexes shows are never used.
On this page ยท 09

Database indexing is the highest-payoff performance skill an application developer can learn: most slow queries are slow because the database reads the whole table when it could read a handful of rows. Run EXPLAIN ANALYZE on slow queries, index the columns you filter, join and sort on (equality columns first, range or sort columns last), index your foreign keys, and remove indexes nothing uses. That covers the large majority of "the app got slow as we grew" problems.

Most slow apps are not slow because of the framework, the ORM or the cloud region. They are slow because of a missing or mis-ordered index. You can get most of the value without becoming a database administrator. This is the version of indexing we wish someone had explained to us before we shipped our first dashboard that timed out once real customers arrived. Examples use Postgres, but the ideas carry over to MySQL and most relational databases.

What a database index actually is

An index is a separate, sorted structure built from one or more columns, with pointers back to the rows in the table. The default in Postgres is a B-tree, a balanced tree the database can descend in a few steps instead of reading every row. The trade is simple: reads get faster, writes get slightly slower because the index must be updated too, and you spend storage. Everything below is learning when that bargain is worth it.

Without an index, a query like WHERE email = 'a@b.com' forces a sequential scan: the database reads every row and checks each one. With a B-tree index on email, it walks the tree to the matching entry directly. On a table of a hundred rows nobody notices the difference. As the table grows into millions of rows, the scan's cost grows with it, while the index lookup barely changes.

Index types you will actually use

B-tree covers most needs, but Postgres ships several index types, each built for a different kind of query:

Index typeGood forTypical example
B-tree (default)Equality, ranges, sorting, prefix LIKE 'abc%'customer_id = 42, created_at > now() - interval '7 days'
GINValues containing many elements: JSONB, arrays, full-text searchmetadata @> '{"plan": "pro"}', tag arrays
GIN with pg_trgmFuzzy and substring text searchname ILIKE '%smith%'
GiSTGeometric data, ranges, nearest-neighbour searchBooking overlaps, location queries
BRINHuge, naturally ordered tablesAppend-only event or log tables by timestamp
HashEquality onlyRarely better than B-tree in practice

If you are unsure, use a B-tree. Reach for the others when the query shape demands it.

Read the query plan, not your intuition

You do not guess at indexing. You ask the database what it is doing. In Postgres, prefix a query with EXPLAIN. EXPLAIN alone shows the plan the database intends to use; adding ANALYZE actually runs the query and reports real timings, and BUFFERS shows how much data it read.

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Because ANALYZE executes the statement, wrap it in BEGIN and ROLLBACK when you inspect an UPDATE or DELETE.

On a large table without a suitable index, the plan will look something like this (illustrative output, trimmed):

Limit
  ->  Sort  (Sort Key: created_at DESC)
        ->  Seq Scan on orders
              Filter: (customer_id = 42)
              Rows Removed by Filter: 999982

Seq Scan plus a huge Rows Removed by Filter is the smell: the database read about a million rows to return eighteen, then sorted them. After adding the right index, the same query becomes:

Limit
  ->  Index Scan using orders_customer_created_idx on orders
        Index Cond: (customer_id = 42)

No sequential scan, no separate sort step. Make this a habit: run the plan before you add an index and after. If the plan did not change, the index is not being used, and you have learned something useful for free.

What to look for in a plan

  • Seq Scan on a large table with a selective filter: likely a missing index.
  • Rows Removed by Filter far larger than the rows returned: the index, if any, is not selective enough or is not being used for that condition.
  • A Sort node before a LIMIT: an index matching the ORDER BY could remove it.
  • Estimated rows wildly different from actual rows: stale statistics. Run ANALYZE on the table.
  • Nested Loop with many loops over an unindexed inner table: often a missing foreign key index.

A sequential scan is not always wrong. If a query returns a large fraction of the table, reading it sequentially is genuinely cheaper than jumping around an index, and the planner knows that.

Composite indexes and why column order matters

Single-column indexes are easy. The part that trips people up is multicolumn (composite) indexes, where order is everything.

A composite index on (customer_id, created_at) is sorted first by customer_id, then by created_at within each customer. Think of a phone book sorted by last name, then first name. That structure serves:

  • WHERE customer_id = 42
  • WHERE customer_id = 42 ORDER BY created_at DESC
  • WHERE customer_id = 42 AND created_at > '2026-01-01'

It does not efficiently serve WHERE created_at > '2026-01-01' on its own, because created_at is only sorted inside each customer's section. This is the leftmost-prefix rule: an index on (a, b, c) helps queries that filter on a, on a and b, or on all three. Postgres 18 added a B-tree skip scan that can sometimes use such an index when the leading column has few distinct values, but do not design around it; design the index for the query.

The practical rule: equality columns first, then the range or sort column last. For the orders query above:

CREATE INDEX CONCURRENTLY orders_customer_created_idx
ON orders (customer_id, created_at DESC);

Matching the index direction to the ORDER BY lets the database read rows already in order and stop after 20. (A B-tree can also be scanned backwards, so for a single sort column the direction matters less than it does when you sort by several columns in mixed directions.) The same shape of index is what makes cursor pagination fast, as we describe in designing REST APIs that last.

Covering indexes and index-only scans

If a query only needs a few columns, you can include them in the index so the database can answer from the index alone, an index-only scan. Postgres expresses the extra payload columns with INCLUDE:

CREATE INDEX CONCURRENTLY orders_customer_created_covering_idx
ON orders (customer_id, created_at DESC)
INCLUDE (id, total);

Every column the query reads must be in the index for this to work, which is why id is included too. Index-only scans also rely on the table being recently vacuumed, so they shine on tables that are read far more than they are written. You trade a larger index for skipping trips back to the table. Worth it for hot read paths, not for everything. When even a tuned index is not fast enough for a hot path, that is usually the moment to add caching with Redis.

Partial indexes

A partial index only covers rows matching a condition. If almost every query targets a small subset, such as pending jobs or active subscriptions, index only that subset:

CREATE INDEX CONCURRENTLY jobs_pending_idx
ON jobs (run_after)
WHERE status = 'pending';

The index stays small and fast even as finished rows pile up, which is exactly why it is the backbone of a Postgres background job queue. Partial unique indexes are also handy for rules like "one active subscription per customer".

Where indexing goes wrong in real apps

These are the patterns we find most often when we review an existing codebase.

Functions hide columns from indexes. WHERE lower(email) = 'a@b.com' will not use a plain index on email, because the index stores the raw value. Either store the value normalised, or build an expression index: CREATE INDEX ON users (lower(email)). The query must use the exact same expression.

Leading wildcards defeat B-trees. WHERE name LIKE '%smith' cannot use a B-tree, because you do not know where in the sort order to start. LIKE 'smith%' can (with the right operator class or a C collation). For substring and fuzzy search, use a GIN index with the pg_trgm extension, or Postgres full-text search.

Foreign keys are not automatically indexed. Postgres indexes primary keys and unique constraints, but not the referencing column on the child side of a foreign key. If you query orders by customer_id (you will), add that index yourself. Missing foreign key indexes also make deletes on the parent table slow, because each delete has to check the child table.

Low-selectivity indexes rarely help. An index on a boolean is_active where most rows are active is mostly overhead. A partial index on the rare value, or a composite index that leads with a selective column, works better.

Type mismatches. Comparing a bigint column to a text parameter, or a timestamptz to a string the ORM formatted oddly, can prevent index use. Check the plan.

ORMs hide the cost. Prisma, Drizzle and friends make it trivial to write a query that joins four tables and filters on an unindexed column, or to fire one query per row in a loop (the N+1 problem). The ORM will not warn you. Turn on query logging in development and watch what actually hits the database:

// Drizzle: log every SQL statement during local development
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
 
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
 
export const db = drizzle(pool, {
  logger: process.env.NODE_ENV === "development",
});

With logging on, copy the slow statement into psql, run EXPLAIN (ANALYZE, BUFFERS), and you will usually find one missing index doing all the damage.

Find the slow queries worth indexing

Do not index speculatively. Find the queries that actually cost you time. The pg_stat_statements extension records execution statistics for every normalised query, and most managed Postgres providers let you enable it with one setting:

SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Sort by total time, not mean time. A 5 ms query called a million times a day matters more than a 2 second report that runs once a week. Work down the list: run the plan, add or adjust an index, confirm the plan changed, and measure again.

The cost side of the ledger

Indexes are not free, and a table with fifteen of them is its own kind of problem. Every INSERT, DELETE, and every UPDATE touching an indexed column has to maintain each affected index. On a write-heavy table, redundant indexes quietly tax every transaction and use memory that could cache hot data instead.

So prune. Postgres tracks index usage in pg_stat_user_indexes:

SELECT relname AS table_name,
       indexrelname AS index_name,
       idx_scan AS times_used,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan ASC;

An index with idx_scan at or near zero after weeks of real traffic is a candidate for removal, unless it backs a unique constraint, which enforces correctness even if no query reads it. Also look for duplicates: an index on (customer_id) is redundant if you already have one on (customer_id, created_at).

Adding indexes safely in production

On a large live table, a plain CREATE INDEX blocks writes until it finishes, which can stall your app. Use CREATE INDEX CONCURRENTLY instead. It takes longer and cannot run inside a transaction block, so many migration tools need a flag to run it outside their usual transaction. If it fails partway, it leaves an invalid index behind that you should drop and rebuild. Drop indexes with DROP INDEX CONCURRENTLY for the same reason.

An indexing checklist for app developers

  1. Enable pg_stat_statements and find the queries with the highest total time.
  2. Run EXPLAIN (ANALYZE, BUFFERS) on each one.
  3. Index foreign keys you filter or join on.
  4. Build composite indexes with equality columns first and range or sort columns last.
  5. Use partial indexes for hot subsets and expression indexes for computed filters.
  6. Add INCLUDE columns only for hot read paths.
  7. Create and drop indexes concurrently in production.
  8. Review unused and duplicate indexes every few months.

Make indexing a habit, not a rescue

You do not need to memorise storage internals. You need a few habits: read the query plan for anything that feels slow, index what you filter, join and sort on in the right order, and delete indexes nothing uses. Do that and most "the app got slow as we grew" problems get solved before a customer ever notices.

Query tuning and schema reviews are a regular part of our PostgreSQL development and performance engineering work. If you would rather hand the slow-query hunt to a team that does this every week, get in touch.

Picking a database in the first place? See the best databases for SaaS in 2026.

FAQ ยท 05 questions

Frequently asked questions

What is a database index?

A database index is a separate data structure, most often a B-tree, that keeps the values of one or more columns sorted along with pointers to the matching rows. The database can search it in a few steps instead of reading every row. It works much like the index at the back of a book.

Which columns should I index?

Index columns that appear in WHERE clauses, JOIN conditions and ORDER BY on queries that run often or touch large tables. Foreign keys are the most commonly missed. Do not index everything: each index slows down writes and uses storage, so add indexes in response to real queries and query plans.

Why is Postgres not using my index?

Common reasons are that the query wraps the column in a function such as lower(), uses a leading wildcard like LIKE '%term', filters on a later column of a composite index without the leading one, or matches so many rows that a sequential scan is genuinely cheaper. Outdated table statistics can also mislead the planner; running ANALYZE on the table refreshes them.

Do indexes slow down inserts and updates?

Yes. Every insert, and every update that changes an indexed column, must also update each affected index. One or two well-chosen indexes are a small cost, but a write-heavy table with many redundant indexes pays it on every transaction. Remove indexes that monitoring shows are unused.

Is it safe to add an index to a large production table?

A plain CREATE INDEX blocks writes to the table while it builds, which can stall your app on a large table. In Postgres, use CREATE INDEX CONCURRENTLY, which builds the index without blocking writes. It takes longer, cannot run inside a transaction block, and can leave an invalid index behind if it fails, which you then drop and retry.

Related service

API & Backend Engineering

Secure, well-documented APIs that scale.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts