[Solved] Mysql query performance slow using group by with aggregate count { >1 million users }

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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 `user_org_xref` ADD INDEX `user_xref_idx_user_id_organization_id` (`USER_ID`,`ORGANIZATION_ID`);
ALTER TABLE `user_tbl` ADD INDEX `user_tbl_idx_acct_id_user_type` (`ACCT_STATUS_ID`,`user_type`);
The optimized query:
SELECT
        count(*) AS col_0_0_,
        usertb0_.ACCT_STATUS_ID AS col_1_0_,
        usertb0_.user_type AS col_2_0_ 
    FROM
        user_tbl usertb0_ 
    INNER JOIN
        user_org_xref userorgxre1_ 
            ON usertb0_.USER_ID = userorgxre1_.USER_ID 
    WHERE
        (
            userorgxre1_.ORGANIZATION_ID IN (
                2
            )
        ) 
        AND (
            usertb0_.ACCT_STATUS_ID IN (
                1, 11, 13, 15, 2
            )
        ) 
    GROUP BY
        usertb0_.ACCT_STATUS_ID,
        usertb0_.user_type 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.