3

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was going to suggest the same solution not only as a workarround but as a, in a way. "better" solution (to just this concrete problem): Despite an index over audit_date column would be more generic (so preferrable because it is more likely to be used for other queries), an index over ` date_trunc(…)` will have much less different keys (so I guess it will be sligtly faster to traverse it, supposing it is a btree) and, more than that: having it will be used to test SINGLE equality instead of two inequalities (2 conditions, one being revense scan…).
4

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);

1 Comment

Great. Time droped to 45 ms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.