Just to complement Lukasz Szozda answer that I find very good.
In cases you cannot modify the SQL (for any reason) it's possible in PostgreSQL to create an index with the specific column and/or column expression combination. In your case:
create index ix1 on tests (sensor_id, date_trunc('month', audit_date));
With this index in place you can use your existing SQL untouched, and get high performance.
You could make expression date_trunc('month', audit_date)
SARGable:
select
sensor_id,
sum(val)
from tests
where sensor_id in (34,35) --index on this column
and audit_date >= cast(date_trunc('month', current_date) as date)
and audit_date < cast(date_trunc('month', current_date) as date)
+ interval '1 month'
group by sensor_id;
And create index:
CREATE INDEX idx ON tests(sensor_id, audit_date);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.