Re: index not always used when selecting on a date field

From: list-pgsql-general(at)news(dot)cistron(dot)nl ("Miquel van Smoorenburg" )
To: pgsql-general(at)postgresql(dot)org
Subject: Re: index not always used when selecting on a date field
Date: 2004-11-08 22:23:31
Message-ID: cmorl3$vjt$1@news.cistron.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

In article <87mzxsjgo4(dot)fsf(at)stark(dot)xeocode(dot)com>,
Greg Stark <gsstark(at)mit(dot)edu> wrote:
>
>Russell Smith <mr-russ(at)pws(dot)com(dot)au> writes:
>
>> now() and CURRENT_DATE, are and cannot be planned as constants.
>> So the planner cannot use an index for them.
>
>It's not that it cannot use an index, but that it doesn't know it should use
>an index. The planner knows that it can't count on now() to be constant so it
>doesn't use the value it has. As far as it's concerned you're comparing
>against an unknown value. And in general the postgres optimizer assumes single
>sided inequalities with unknown constants aren't selective enough to justify
>an index scan.
>
>The easiest work-around is probably just putting in a bogus second inequality
>to make it a range. The planner generally assumes ranges are selective enough
>to justify index scans.

Well, strangely enough, after checking once more, that works
with 7.3, but with 7.4 it doesn't.

techdb2=> explain select * from lines where (removed > CURRENT_DATE AND removed < '9999-01-01');
QUERY PLAN
--------------------------------------------------------------------------------
Seq Scan on lines (cost=0.00..259.89 rows=2189 width=178)
Filter: ((removed > ('now'::text)::date) AND (removed < '9999-01-01'::date))
(2 rows)

With 7.3, this query used the index, while with 7.4 it doesn't.
Using an immutable function that returns CURRENT_DATE indeed
makes it work as I expected:

techdb2=> explain select * from lines where removed > today();
QUERY PLAN
---------------------------------------------------------------------------------
Index Scan using lines_removed_idx on lines (cost=0.00..4.85 rows=1 width=178)
Index Cond: (removed > '2004-11-08'::date)
(2 rows)

Thanks for the advice,

Mike.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Marc G. Fournier 2004-11-08 22:31:55 Re: RFD: comp.databases.postgresql.general
Previous Message Oliver Jowett 2004-11-08 21:55:55 Re: [JDBC] Using Postgres with Latin1 (ISO8859-1)