Re: Big table - using wrong index - why? - Mailing list pgsql-sql

From Tom Lane
Subject Re: Big table - using wrong index - why?
Date
Msg-id 21764.996520806@sss.pgh.pa.us
Whole thread Raw
In response to Big table - using wrong index - why?  ("Chris Ruprecht" <chrup999@yahoo.com>)
List pgsql-sql
"Chris Ruprecht" <chrup999@yahoo.com> writes:
> phones=# explain select * from phonelog where entity = '001' and pseq >=
> 9120 and pseq <= 9123;
> NOTICE:  QUERY PLAN:

> Index Scan using i_pl_loadtimestamp on phonelog  (cost=0.00..209247.39
> rows=607 width=137)

Your problem is that pseq is of type int8 (bigint) but the constants
9120 and 9123 are of type int4 (integer).  The system does not currently
recognize cross-datatype comparisons as being compatible with indexes.
To make the query indexable, you need to cast the constants to be the
same type as the indexed column.  Here's a simplified example:


regression=# create table foo (f1 int8 primary key);
NOTICE:  CREATE TABLE/PRIMARY KEY will create implicit index 'foo_pkey' for table 'foo'
CREATE
regression=# explain select * from foo where f1 = 42;
NOTICE:  QUERY PLAN:

Seq Scan on foo  (cost=0.00..22.50 rows=1 width=8)

EXPLAIN
regression=# explain select * from foo where f1 = 42::int8;
NOTICE:  QUERY PLAN:

Index Scan using foo_pkey on foo  (cost=0.00..4.82 rows=1 width=8)

EXPLAIN


Another way is to write the constants as unknown-type literals (ie,
strings) and let the system decide that you meant to let them be int8:


regression=# explain select * from foo where f1 = '42';
NOTICE:  QUERY PLAN:

Index Scan using foo_pkey on foo  (cost=0.00..4.82 rows=1 width=8)

EXPLAIN


Variants of this problem arise with int2 and float4 columns, BTW.

This is on the to-fix list... see the pghackers list archives for
excruciatingly long discussions about how to fix it without breaking
other cases...
        regards, tom lane


pgsql-sql by date:

Previous
From: "Chris Ruprecht"
Date:
Subject: Re: Big table - using wrong index - why?
Next
From: Gary Stainburn
Date:
Subject: union in subselect?