← Back to PostgreSQL, page 4

postgresql-0078 · Hard senior

A query on an indexed bigint column does a sequential scan when the application passes a numeric parameter. Why?

When the parameter's type differs from the column's, PostgreSQL may cast the column instead of the value; WHERE id = 42.0 compares id::numeric to a numeric, and an index on id cannot be used for that expression. The fix is passing parameters of the column's type, or casting the parameter explicitly. ORMs and drivers that send numeric or text types are a common source.

Full answer

Test data:

sql
CREATE TABLE payments (id bigint PRIMARY KEY, amount int);
INSERT INTO payments SELECT g, g % 1000 FROM generate_series(1, 50000) g;
ANALYZE payments;
sql
EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42;

PostgreSQL returns:

text
Index Scan using payments_pkey on payments
  Index Cond: (id = 42)
sql
EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0;

Result on PostgreSQL 17:

text
Seq Scan on payments
  Filter: ((id)::numeric = 42.0)
sql
PREPARE by_id(numeric) AS SELECT amount FROM payments WHERE id = $1; EXPLAIN (COSTS OFF) EXECUTE by_id(42);

Result:

text
Seq Scan on payments
  Filter: ((id)::numeric = '42'::numeric)
sql
EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0::bigint;

Output:

text
Index Scan using payments_pkey on payments
  Index Cond: (id = '42'::bigint)

An integer literal uses the primary key index. The literal 42.0 is numeric, and the plan shows a sequential scan with the filter (id)::numeric = 42.0 on all 50,000 rows. A prepared statement whose parameter is declared numeric behaves the same, which is how this appears in applications: the driver declares the parameter type, not the value. Casting the parameter to bigint restores the index scan. Check for such casts on the column side of conditions in EXPLAIN output, and declare parameter types to match the columns.

sql
CREATE TABLE payments (id bigint PRIMARY KEY, amount int);
INSERT INTO payments SELECT g, g % 1000 FROM generate_series(1, 50000) g;
ANALYZE payments;

EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42;

EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0;

PREPARE by_id(numeric) AS SELECT amount FROM payments WHERE id = $1; EXPLAIN (COSTS OFF) EXECUTE by_id(42);

EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0::bigint;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Mismatched types can cast the column
  • Casting the column prevents index use
  • Drivers choose parameter types
  • Cast the parameter, not the column
  • Look for casts in EXPLAIN filters

Common mistakes

  • Sending numeric parameters for integer keys
  • Comparing text columns with integer parameters

Follow-ups

  • Why can PostgreSQL not cast the numeric to bigint itself?
  • How do you see parameter types in pg_stat_statements?

Tips

  • Point at the cast in the filter