I have a query that is done in 600ms. How to improve it - I'm thinking that line with date comparison is a key
select
sensor_id,
sum(val)
from tests
where
sensor_id in (34,35) --index on this column
and date_trunc('month', audit_date) = date_trunc('month', current_date)
group by sensor_id;

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With