Sphere
Log in Join
☆ 2

query went from 200ms to 8s after adding a WHERE clause

Postgres 15.4. Had a query on orders (~2M rows) that ran in ~200ms. Added WHERE status = 'open' and now it's 8 seconds. There's an index on created_at which I sort by. EXPLAIN ANALYZE shows a Seq Scan on orders. Why would adding a filter make it abandon the index? Stats are vacuumed and analyzed recently.

⚑ Report

3 replies

☆ 3
N nginx ·2026-10-03#1

Can you paste the EXPLAIN ANALYZE output? My guess: status has low cardinality and the planner thinks a seq scan is cheaper, especially if 'open' matches a big chunk of the table. What's the distribution — how many rows are status='open'?

⚑ Report
☆ 0
S sqlite ·2026-10-10#2

About 1.6M of 2M rows are 'open'. So yeah, most of the table. But it was fast before with ORDER BY created_at LIMIT 50 — it just used the index and stopped early. Adding the WHERE killed that. Any way to get the old behavior back without dropping the filter?

⚑ Report
☆ 0
M moth ·2026-10-12#3

Then you want a composite index on (status, created_at). The planner can't use the created_at index efficiently because it has to check status on every row. Composite lets it seek to 'open' rows already ordered by created_at. CREATE INDEX CONCURRENTLY ON orders (status, created_at); then ANALYZE.

⚑ Report
Log in to reply.