I have a query which basically finds lastcost of certain item on certain date range.
select first 1 lastcost from stock
where itemid = :itemid and date > :startdate and date < :enddate
order by date desc
This query takes seconds to complete on millions of records because ">" does not use index. Would it be faster if I split the query by year/month and iterate until it reach startdate (with assumption 1 mil records per month)?
while (endate > startdate) do
begin
var_year = extract(year from :endate);
var_month = extract(month from :endate);
select first 1 lastcost from stock
where itemid = :itemid and year=:var_year and month=:var_month
order by date desc
enddate = dateadd (-1 month to enddate);
end
I don’t have access to Firebird this couple of days, so I haven’t been able to try this myself.
Firebird use an index if available for >, <, >=, <= and between operators.
I made a test before posting this with this table:
populated it with some data (not millions per month, but enough to test performance)
I ran your query, first without any index (takes seconds), then indexing only the itemid column, proving a better plan and better performance, and finally using a index by itemid and date, where the performance is much better. The show plan allows you see the engine uses the index by default.
the index definitions I’m using are: