Skip to content
Advertisement

Optimize SQLite Query using GROUP BY

I am trying to optimize my query which uses GROUP BY. But can’t it takes too long time.

I have a virtual table which contains 3 columns:

I want the group to be just as the query below, but it just takes a bit too long to run. For example I tried this first which works pretty good but still I wonder if I can make it faster:

Then:

But it still takes long time to query. I’m trying to use JOIN because I heard it is usually faster but can’t really succed. Any advice would help!

Advertisement

Answer

Why did you choose to set the condition in the HAVING clause?
With your code the condition is checked after all the aggregations are finished.
Your condition does not involve any aggregated column so there is no reason to use it in the HAVING clause.
It would make more sense to set it in a WHERE clause so the dataset is filtered and then GROUP BY is applied for aggregation:

You could also try EXISTS which sometimes performs better:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement