I'm trying to speed up this PostgreSQL query to find previous entries "on this day" in past years from a table. I currently have the query below:
select * from sample
where date_part('month', "timestamp") = date_part('month', now())
and date_part('day', "timestamp") = date_part('day', now())
order by "timestamp" desc;
This seems to get the intended result, but it is running much slower than desired. Is there a better approach for comparing the current month & day?
Also, would there be any changes to do a similar search for "this hour" over the past years? Similar to the following:
select * from sample
where date_part('month', "timestamp") = date_part('month', now())
and date_part('day', "timestamp") = date_part('day', now())
and date_part('hour', "timestamp") = date_part('hour', now())
order by "timestamp" desc;
The data is time-series in nature, using TimescaleDB as the database. Here is the current definition:
CREATE TABLE public.sample (
"timestamp" timestamptz NOT NULL DEFAULT now(),
entity varchar(256) NOT NULL,
quantity numeric NULL
);
CREATE INDEX sample_entity_time_idx ON public.sample (entity, "timestamp" DESC);
CREATE INDEX sample_time_idx ON public.sample ("timestamp" DESC);