I have fairly long and complex SQL query that is run against PostgreSQL 8.3. Part of the query involves filtering on a range of dates ending with today, like this:
where ...
and sp1.price_date between current_date::date - '1 year'::interval and current_date::date
and sp4.price_date between current_date::date - '2 weeks'::interval and current_date::date
and sp5.price_date = (select sp6.price_date
from stock_prices sp6
where sp6.stock_id = s.stock_id
and sp6.price_date < current_date::date
order by sp6.price_date desc
limit 1)
...
This query takes almost 5 minutes to run (the first time) and about 1.5 minutes the second time. From looking at the EXPLAIN ANALYZE output it seems that current_date is the problem. So I tried replacing it with a hardcoded date, like this:
where ...
and sp1.price_date between '2009-09-30'::date - '1 year'::interval and '2009-09-30'::date
and sp4.price_date between '2009-09-30'::date - '2 weeks'::interval and '2009-09-30'::date
and sp5.price_date = (select sp6.price_date
from stock_prices sp6
where sp6.stock_id = s.stock_id
and sp6.price_date < '2009-09-30'::date
order by sp6.price_date desc
limit 1)
...
The query then ran in half a second! That's great, except that the date occurs in a total of 10 places in the query and, of course, I don't want the user to have to manually change it in 10 places. In MS SQL Server I would simply declare a variable with the value of the current date and use that, but apparently that's not possible in plain SQL in Postgres.
What can I do to make this query run fast while automatically using the current date?