[Solved] MySQL GROUP_CONCAT extremely slow with multiple constraints but fast with one

EverSQL Database Performance Knowledge Base

MySQL GROUP_CONCAT extremely slow with multiple constraints but fast with one

Database type:

The query below runs extremely fast (Less than 1 second) with one ID

SELECT ID, GROUP_CONCAT(CODE SEPARATOR ' ') 
FROM TABLE
WHERE TYPE='A' AND ID IN ( 1 )
GROUP BY ID;

But extremely slow (Over 10 seconds) when run with more than one ID

SELECT ID, GROUP_CONCAT(CODE SEPARATOR ' ')
FROM TABLE
WHERE TYPE='A' AND ID IN (1, 2)
GROUP BY ID;

I think it's because MySQL tries to perform the GROUP_CONCAT on all IDs first, then compares it with the IN constraint. Any ideas?

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 `TABLE` ADD INDEX `table_idx_type_id` (`TYPE`,`ID`);
The optimized query:
SELECT
        TABLE.ID,
        GROUP_CONCAT(TABLE.CODE SEPARATOR ' ') 
    FROM
        TABLE 
    WHERE
        TABLE.TYPE = 'A' 
        AND TABLE.ID IN (
            1
        ) 
    GROUP BY
        TABLE.ID 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.