[Solved] INNER JOIN causes query executes very long

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. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Avoid Subselect When Selecting MAX/MIN Per Group (query line: 7): Constant subquery results are usually not cached by the database, especially in non-recent database versions. Therefore, a constant subquery in a WHERE clause will be fully evaluated for every row the WHERE clause will examine, which can significantly impact query performance. Use the method mentioned in the example instead.
  3. 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.
  4. Sort and Limit Before Joining (modified query below): In cases where the joins aren't filtering any rows, it's possible to sort and limit the amount of rows using a subquery in the FROM clause, before applying the joins to all other tables.
Optimal indexes for this query:
ALTER TABLE `citizens_history` ADD INDEX `citizens_history_idx_update_to` (`update_id_to`);
ALTER TABLE `citizens_history` ADD INDEX `citizens_history_idx_experience` (`experience`);
The optimized query:
SELECT
        ch1.* 
    FROM
        (SELECT
            citizens_history1.id AS citizens_history1_id,
            citizens_history1.update_id_to AS citizens_history1_update_id_to 
        FROM
            citizens_history AS citizens_history1 
        ORDER BY
            citizens_history1.experience DESC LIMIT 100) AS citizens_history1 
    LEFT JOIN
        citizens_history AS citizens_history2 
            ON (
                citizens_history2.id = citizens_history1.citizens_history1_id
            ) 
            AND (
                citizens_history1.citizens_history1_update_id_to < citizens_history2.update_id_to
            ) 
    WHERE
        (
            1 = 1
        ) 
        AND (
            citizens_history2.update_id_to IS NULL
        ) LIMIT 100

Related Articles



* original question posted on StackOverflow here.