Skip to content
isam.chajia
Engineering

PostgreSQL indexing basics every web developer should know

B-tree, unique and partial indexes, and how to read a query plan before you add one.

Isam Chajia8 min read
Planning sketches and a pen on cream paper

An index trades a little write cost and disk space for much faster reads. Used well, it is the cheapest performance win in a database-backed app.

What an index actually does

Without an index, a filter forces a table scan — every row is read. With one, PostgreSQL can jump straight to the matching rows. The default B-tree index handles equality and range queries well.

create index invoices_org_created_idx
  on invoices (org_id, created_at desc);

Read the query plan first

Before adding an index, look at what the database is actually doing. If the plan already uses an index, a second one probably will not help.

explain analyze
select * from invoices
where org_id = '...'
order by created_at desc
limit 20;

Indexes that pay off

  • Foreign keys you filter or join on often.
  • Columns used in ORDER BY alongside a filter.
  • A partial index when you only ever query a subset of rows.

Remove indexes you no longer use. Every one of them has to be maintained on every write.

  • PostgreSQL
  • Databases
  • Performance
Engineering8 min read

Designing REST APIs that age well

Resource naming, status codes, pagination and versioning — the decisions that keep an API predictable years after launch.

Available for new work

Enjoying the writing?

If an article sparked an idea for your product or team, I'd be glad to hear about it.

Replies within 2 working daysMarrakech, Morocco