Sphere
Log in Join
☆ 16

postgres query doing a seq scan despite an index

Postgres 15. A query on orders(customer_id) is doing a sequential scan even though there's a btree index on customer_id. EXPLAIN ANALYZE:

Seq Scan on orders (cost=0.00..18334.00 rows=1 width=72) (actual time=0.02..120.3 rows=1 loops=1)
Filter: (customer_id = 4242)
Rows Removed by Filter: 500000
Planning Time: 0.08 ms
Execution Time: 120.4 ms

Why won't it use the index? The table has 500k rows.

⚑ Report

4 replies

☆ 0
T tiny29 ·2026-10-19#1

First check the index actually exists and is valid: \d orders and SELECT indexdef FROM pg_indexes WHERE tablename='orders'. Also check statistics with ANALYZE orders;. Postgres picks a seq scan when it thinks the filter matches enough rows that a scan is cheaper. For a single match on 500k rows, an index scan should win, so stale stats or a mismatched type are likely.

⚑ Report
☆ 0
G ghost ·2026-10-19#2

There is an index. customer_id is bigint in the table, and my query passes a parameter from Python (psycopg3). Could a type mismatch be forcing a cast that the index can't use? I will give that a shot and see how it goes.

⚑ Report
☆ 0
G glitch ·2026-10-26#3

Yes, that's a classic. If the parameter arrives as text or int4 and Postgres has to cast the column, the index may become unusable. Check EXPLAIN (VERBOSE) to see the filter expression. Cast the parameter explicitly: customer_id = %s::bigint. Also confirm you're connecting to the database you think you are.

⚑ Report
☆ 0
S stack ·2026-11-01#4

It was the parameter type. psycopg3 was sending the value in a way that led to a cast. Adding ::bigint to the parameter let the index kick in: index scan, 0.05ms. Also ran ANALYZE to refresh stats. Both helped, but the cast was the real fix.

⚑ Report
Log in to reply.