Skip to content
Aitsam Ahad

Software Engineering

Why the index made it slower

So the planner figured it'd touch about forty rows, picked the index, and then walked four and a half million.

Why the index made it slower — slower

So we added an index to make this query faster. It got four hundred times slower.

The mental model

Here's the one idea you need. The planner never actually reads your data. It reads a summary of it.

the planner chooses a strategy before a single row is touched
the planner chooses a strategy before a single row is touched

The mechanism

And that summary is a histogram. A few hundred buckets, standing in for a few hundred million rows.

Now, our data wasn't evenly spread. One customer had ninety four percent of the rows.

So the planner figured it'd touch about forty rows, picked the index, and then walked four and a half million.

rows per bucket, as the planner sees them rows per bucket, as they actually were Code

Back to the anomaly

A sequential scan would've read that table once. The index read it four and a half million times. One row at a time.

execution time
execution time

Sources

  • planner uses histogram statistics
  • Query Planner
  • Indexes
  • Postgres

Written by

Aitsam Ahad

Senior Full-Stack Engineer with 6+ years architecting scalable web applications in Node.js, TypeScript, Express and NestJS on the backend and React/Next.js on the front. Currently Principal Software Engineer at TEO International, Islamabad.

Explore my experience