![]() | |
![]() |
| | Thread Tools | Display Modes |
#1
| |||
| |||
|
#2
| |||
| |||
|
|
I have a database with a btree index on the 'removed' field, which is of type 'date'. However it isn't being used: techdb2=> explain select * from lines where removed > CURRENT_DATE; QUERY PLAN ------------------------------------------------------------ Seq Scan on lines (cost=0.00..243.47 rows=2189 width=324) Filter: (removed > ('now'::text)::date) (2 rows) Now the weird thing is that if I select a range it is being used: techdb2=> explain select * from lines where removed > CURRENT_DATE and removed < '9999-01-01'; QUERY PLAN ------------------------------------------------------------------------------------ Index Scan using lines_removed_idx on lines (cost=0.00..120.56 rows=33 width=324) Index Cond: ((removed > ('now'::text)::date) AND (removed < '9999-01-01'::date)) (2 rows) Why is this? (Tested with both 7.3.2 and 7.4.6) Mike. now() and CURRENT_DATE, are and cannot be planned as constants. |
#3
| |||
| |||
|
|
now() and CURRENT_DATE, are and cannot be planned as constants. So the planner cannot use an index for them. |
#4
| |||
| |||
|
|
Russell Smith <mr-russ (AT) pws (DOT) com.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. |
#5
| |||
| |||
|
|
techdb2=> explain select * from lines where (removed > CURRENT_DATE AND removed < '9999-01-01'); With 7.3, this query used the index, while with 7.4 it doesn't. |
#6
| |||
| |||
|
|
list-pgsql-general (AT) news (DOT) cistron.nl ("Miquel van Smoorenburg" ) writes: techdb2=> explain select * from lines where (removed > CURRENT_DATE AND removed < '9999-01-01'); With 7.3, this query used the index, while with 7.4 it doesn't. Perhaps you hadn't ANALYZEd in 7.3? AFAICS 7.3 and 7.4 behave essentially alike on this point, given comparable statistics. One thing I did notice in looking at this is that the preferential treatment for range constraints only applies when *both* sides of the range are un-estimatable. So you need to write something like WHERE (removed > CURRENT_DATE AND removed < CURRENT_DATE + 10000) to get it to work nicely. I'll see if I can improve on that for 8.0; seems like the way you tried ought to work, too. |
![]() |
| Thread Tools | |
| Display Modes | |
| |