Skip to content
Blog

Engineering

Database indexing explained

Database indexing explained: why queries go slow, how B-trees work, when composite indexes win, and why EXPLAIN ANALYZE should be a reflex.

By Pykero Agency · Engineering teamJul 8, 20265 min read

TL;DR

Most slow queries trace back to a missing or misused index. Understand the B-tree structure, composite index ordering, and EXPLAIN ANALYZE and you can fix performance issues on purpose rather than by luck.

Branching index tree accelerating a data lookup

Almost every slow-database complaint traces back to a missing or misused index. Database indexing explained properly comes down to three things: one data structure, one SQL command, and one habit. Get those right and a ten-second query becomes a ten-millisecond one on purpose rather than by accident.

Database indexing explained: the B-tree structure

A database index is a separate, sorted data structure that lets the engine find rows without reading the whole table. Without one, the engine performs a sequential scan: every row, every page, top to bottom. With one, it jumps directly to the matching rows.

Most indexes are B-trees. B-trees keep values sorted, which is why they speed up equality checks (=), range queries (<, >, BETWEEN), sorting, and prefix matches. They do nothing for a leading wildcard: LIKE '%foo' has no sorted starting point, so a B-tree cannot help.

PostgreSQL also ships with hash indexes (equality only), GIN indexes (full-text search and JSONB), and GiST (geometric and range types). B-tree covers roughly 90% of what you will encounter day to day.

Index what you filter, join, and sort on

Any column that regularly appears in a WHERE clause, a JOIN condition, or an ORDER BY is a candidate. Foreign keys almost always need an index because you will join on them constantly and the table will grow.

For multi-column queries, a composite index beats two separate single-column indexes. Column order is where most people go wrong. An index on (tenant_id, created_at) supports queries filtering by tenant_id alone, or by both columns together. It does not support queries filtering by created_at alone. The leading column must be the one that appears most often in isolation. Put the most selective, most-frequently-filtered column first.

Partial indexes are worth knowing about and are badly underused. If 95% of your queries filter on status = 'active', an index with that condition baked in is much smaller and faster than a full-column index. PostgreSQL supports this with a WHERE clause on the CREATE INDEX statement.

Learn to read EXPLAIN ANALYZE

You do not have to guess whether an index is used. Run EXPLAIN ANALYZE on any query that feels slow and read the output.

  • Seq Scan on a large table in a hot query path means the engine is reading everything. That is the red flag.
  • Index Scan means the engine used the index to locate rows, then fetched them from the table.
  • Index Only Scan means the index contained all the columns the query needed. No table fetch at all. Fastest option.
  • Row estimate vs. actual rows: when these diverge badly, the planner's statistics are stale. Run ANALYZE on the table to refresh them.

Make EXPLAIN ANALYZE a reflex before and after adding an index. It turns performance work from guesswork into measurement. The teams that struggle with database performance have usually never looked at a query plan, not because the skill is hard to acquire but because nobody formed the habit.

Indexes are not free

Every INSERT, UPDATE, and DELETE must update every affected index. Over-indexing a write-heavy table slows down exactly the operations the application depends on. Disk space matters too, though it is rarely the binding constraint.

Index deliberately:

  1. Add indexes to support real, measured slow queries. Hypothetical future queries are a poor reason.
  2. Drop indexes nothing uses. PostgreSQL tracks this in pg_stat_user_indexes. Zero scans since the last stats reset means the index is dead weight.
  3. Remove redundant indexes where a composite already covers a single-column case.

pg_stat_user_indexes is one of the most useful views in PostgreSQL and most teams have never queried it.

The one loop that fixes most problems

Write the query. Run EXPLAIN ANALYZE. Add the index the plan is clearly asking for. Measure again. Repeat consistently and slow-database fire drills mostly disappear. There is no secret knowledge involved. Most teams that struggle have just never closed the loop between writing SQL and reading what the planner actually does with it.

For more on how these decisions compound at scale, the PostgreSQL for startups post covers schema design and operational concerns beyond indexing alone.

If your app is crawling and the database looks like the cause, let's talk.

database indexing explainedpostgresql indexingcomposite index postgresqlexplain analyze postgresqlslow database queriesb-tree index database

Frequently asked questions

what is a database index

An index is a separate, sorted data structure the engine uses to find rows without scanning the whole table. Most are B-trees, which support equality checks, range queries, sorting, and prefix matches.

when should I add a database index

Add one when a column appears regularly in WHERE clauses, JOIN conditions, or ORDER BY. Foreign keys almost always need one. Confirm with EXPLAIN ANALYZE before and after.

what is a composite index and does column order matter

A composite index covers multiple columns in a fixed order. An index on (tenant_id, created_at) supports filtering by tenant_id alone or both columns together, but not by created_at alone. Put the most selective, most-filtered column first.

how do I check if postgresql is using my index

Run EXPLAIN ANALYZE on the query. Index Scan or Index Only Scan means the index is working. Seq Scan on a large table means it is not. The pg_stat_user_indexes view shows how often each index has been used since the last stats reset.

How Pykero can help

Services related to this article.

Building something like this?

Pykero Agency designs and ships production web, mobile, SaaS, and AI products.

Talk to us

Discussion

Be the first to comment.

Related reading