Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - How make simple query faster

Tags:

sql

postgresql

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;

enter image description here

like image 388
WuBe Avatar asked Dec 28 '25 00:12

WuBe


1 Answers

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.

like image 95
The Impaler Avatar answered Dec 30 '25 14:12

The Impaler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!