[Solved] improve performance of group by clause with SUM aggregation function

EverSQL Database Performance Knowledge Base

improve performance of group by clause with SUM aggregation function

I have a query that groups results in the order of 300,000 rows.

What I've tried is to create an index with the group by columns. When I run the query without the SUM function, the query seems to run pretty fast, but when I add a column with SUM, then the response time increases a lot. For example no SUM query response in less than 1s (paginated), SUM query response in 20s.

Supposing there's a index on a,b,c,d,e columns and there are 300,000 records in TableA :

response in less than 1s (in SQL developer, which shows first 50 rows):

SELECT a,b,c,d
FROM tableA
GROUP BY
a,b,c,d

response in 18s (in SQL developer, which shows first 50 rows):

SELECT a,b,c,d,SUM(e)
FROM tableA
GROUP BY
a,b,c,d

Any suggestions?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `tableA` ADD INDEX `tablea_idx_a_b_c_d` (`a`,`b`,`c`,`d`);
The optimized query:
SELECT
        tableA.a,
        tableA.b,
        tableA.c,
        tableA.d 
    FROM
        tableA 
    GROUP BY
        tableA.a,
        tableA.b,
        tableA.c,
        tableA.d 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.