For the query above, the following recommendations will be helpful as part of the SQL tuning process. You'll find 3 sections below:
Description of the steps you can take to speed up the query.
The optimal indexes for this query, which you can copy and create in your database.
An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
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.
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.
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.
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:
citizens_history1.id AS citizens_history1_id,
citizens_history1.update_id_to AS citizens_history1_update_id_to
citizens_history AS citizens_history1
citizens_history1.experience DESC LIMIT 100) AS citizens_history1
citizens_history AS citizens_history2
citizens_history2.id = citizens_history1.citizens_history1_id
citizens_history1.citizens_history1_update_id_to < citizens_history2.update_id_to
1 = 1
citizens_history2.update_id_to IS NULL
) LIMIT 100