Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

PostgreSQL Indexes Explained: Make Slow Queries Fast

How PostgreSQL indexes work, how to read EXPLAIN ANALYZE, when to use B-tree, composite, partial and GIN indexes, and the mistakes that make indexes useless.

Sumit KumarUpdated Oct 8, 20263 min readPostgreSQL
PostgreSQL Indexes Explained: Make Slow Queries Fast

Your app is fast with 1,000 rows and painfully slow with 1,000,000. The most common reason is a missing index. An index is like the index at the back of a book: instead of reading every page to find "closures", you jump straight to the right page.

What happens without an index#

Take a table of orders and a common query:

SQL
SELECT * FROM orders
WHERE customer_id = 4821;

Without an index on customer_id, PostgreSQL must read every row and check it. This is a sequential scan. Its cost grows with the table, so the query gets slower every day your app grows.

Sequential scan reads every row (118 ms) while an index scan jumps straight to the matching rows (0.09 ms)

Reading the query plan#

Put EXPLAIN ANALYZE in front of a query to see what PostgreSQL actually did and how long it took:

SQL
EXPLAIN ANALYZE
SELECT * FROM orders WHERE customer_id = 4821;
Text
Seq Scan on orders
  (cost=0.00..20834.00 rows=12 width=64)
  (actual time=0.41..118.30 rows=11 loops=1)
  Filter: (customer_id = 4821)
  Rows Removed by Filter: 999989
Execution Time: 118.35 ms

The warning signs: Seq Scan on a big table, and Rows Removed by Filter close to the table size. It read a million rows to return 11.

Adding an index#

SQL
CREATE INDEX idx_orders_customer
  ON orders (customer_id);
Text
Index Scan using idx_orders_customer on orders
  (actual time=0.03..0.06 rows=11 loops=1)
  Index Cond: (customer_id = 4821)
Execution Time: 0.09 ms

Same result, about a thousand times faster. The default index type is a B-tree: a sorted, balanced tree that finds a value in a few steps, even among millions of rows.

B-tree lookup for 4821: start at the root, follow the matching branch down a few levels and land on the leaf that points to the rows
Warning

On a busy production table, a plain CREATE INDEX blocks writes until it finishes. Use CREATE INDEX CONCURRENTLY instead. It takes longer but lets inserts and updates continue.

Composite indexes and column order#

For queries that filter on several columns, one index can cover them all:

SQL
CREATE INDEX idx_orders_customer_date
  ON orders (customer_id, created_at);

Column order matters. This index works like a phone book sorted by last name, then first name. It helps:

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

But it usually doesn't help WHERE created_at > '2026-01-01' on its own, because the first column isn't used. A good rule: put columns used with = first, and range or sort columns after.

Composite index column order: queries on the first column, or the first and second together, use the index; a query on the second column alone cannot

Other index types worth knowing#

IndexGood for
B-tree (default)=, <, >, BETWEEN, ORDER BY
PartialOnly some rows, e.g. active orders
ExpressionSearching on a computed value
GINJSONB, arrays, full-text search
BRINHuge tables naturally ordered by time
SQL
-- Partial: only index rows you query often
CREATE INDEX idx_orders_pending
  ON orders (created_at)
  WHERE status = 'pending';

-- Expression: case-insensitive email lookup
CREATE INDEX idx_users_email_lower
  ON users (lower(email));
-- used by: WHERE lower(email) = 'a@b.com'

-- GIN: search inside JSONB
CREATE INDEX idx_products_attrs
  ON products USING gin (attributes);
-- used by: WHERE attributes @> '{"color": "red"}'

When an index won't be used#

  • A function on the column: WHERE lower(email) = ... can't use a plain index on email. Create an expression index.
  • Leading wildcard: LIKE '%son' can't use a B-tree. (LIKE 'son%' can, with the right operator class.)
  • Type mismatch: comparing a text column to a number forces a conversion.
  • Low selectivity: if a query returns a large share of the table, a sequential scan really is faster, and the planner picks it on purpose.
  • Stale statistics: after big data changes, run ANALYZE orders; so the planner has accurate numbers.

Indexes are not free#

Every index takes disk space and must be updated on every INSERT, UPDATE and DELETE. Ten indexes on a write-heavy table can slow writes noticeably. Index for the queries you actually run, and remove indexes that are never used. You can find them with:

SQL
SELECT relname, indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY relname;
Tip

Foreign key columns are not indexed automatically in PostgreSQL. If you join or delete on orders.customer_id, add the index yourself.

Key takeaways#

  • Use EXPLAIN ANALYZE to find sequential scans on large tables.
  • B-tree is the default and handles equality, ranges and sorting.
  • In composite indexes, put equality columns first, then range or sort columns.
  • Use partial, expression and GIN indexes for special cases, and drop unused indexes.