I am using PostgreSQL, and I use the following query:
SELECT r.name,count(r.name)
from rooms r
where to_date(dateinput,'YYYYMMDD') between r.start_date and r.end_date
or to_char(r.end_time,'HH24:MI:SS')<> '00:00:00')
and (r.name in ('nameA','nameB'))
group by r.name
When my table has 900.000 rows, it is very slow. I create an index on the columns start_date, end_date and name. It executes in 1543 ms. end_time is of data type time without time zone.
But when I change the query to
SELECT r.name,count(r.name)
from rooms r
where cast(dateinput as date) >= r.start_date
and cast(dateinput as date) < r.end_date
and r.name in ('nameA','nameB')
or to_char(r.end_time,'HH24:MI:SS')<> '00:00:00')
and (r.name in ('nameA','nameB'))
group by r.name
the execution time is reduced to 786 ms. I think to_date and between make the index inoperable. I can't find any documentation or example that explains why the index cannot be used when using to_date and between. I don't know why modifying the query reduces the time to 786 ms. Can anyone help me?
nameAandnameBchange or are they always the same?