Sphere
Log in Join
☆ 4

postgres EXPLAIN shows index scan but query still slow

Postgres 15. EXPLAIN ANALYZE for a report query shows it's using the right index, but the query takes 8 seconds:

Index Scan using events_ts_idx on events (cost=0.43..52000.00 rows=100000 width=64) (actual time=0.03..7900.00 rows=100000 loops=1)
Index Cond: (ts >= '2026-01-01'::date)
Buffers: shared hit=98000

It fetches 100k rows. Is the index scan itself the problem, or is it something else? Been going in circles on this for a day.

⚑ Report

4 replies

☆ 0
C cache ·2026-10-16#1

The index scan is fine, it's the 100k rows and the buffers. 98k shared buffer hits means lots of heap fetches. If those rows are scattered across the table, each is a random I/O. A covering index (INCLUDE the columns you select) or a bitmap heap scan via a better index could help. Also check if you're actually selecting columns that force heap lookups.

⚑ Report
☆ 0
C cache28 ·2026-10-20#2

I'm selecting about 6 columns. Could a covering index with INCLUDE avoid the heap fetches? And would VACUUM help with the scattered rows? I'll test a covering index on a copy of the table first, since adding it on the live table would take a lock. The row count is the bigger issue though, so I'm also looking at what the report actually needs to return.

⚑ Report
☆ 0
P plastic17 ·2026-10-27#3

A covering index with those 6 columns INCLUDEd can enable index-only scans if the visibility map is set (which VACUUM helps with). But 100k rows is a lot to return regardless; if the client needs all of them, you're paying real transfer cost. Consider pagination or aggregating in SQL. Also EXPLAIN (ANALYZE, BUFFERS) you already have, keep using it.

⚑ Report
☆ 0
C cardboard ·2026-10-28#4

Added a covering index and ran VACUUM, got index-only scans and cut it to ~2s. The remaining cost is genuinely returning 100k rows, so I moved the report to paginate. The index wasn't the villain, the row count was. That has been my experience anyway.

⚑ Report
Log in to reply.