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:
- 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 Subqueries (query line: 7): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
- 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 `record` ADD INDEX `record_idx_file_id_status_id` (`file_group_id`,`status_id`);
ALTER TABLE `record_meta_text` ADD INDEX `record_text_idx_column_id_record_id` (`column_id`,`record_id`);
The optimized query:
col_title AS col_title,
rmt_2780.value AS col_2780,
rmt_2781.value AS col_2781,
rmt_18474.value AS col_18474
r.title AS col_title,
r.id AS r_id
r.file_group_id = 2350
AND r.status_id = 1 LIMIT 50) r
record_meta_text AS rmt_2780
ON rmt_2780.record_id = r.r_id
AND rmt_2780.column_id = 2780
record_meta_text AS rmt_2781
ON rmt_2781.record_id = r.r_id
AND rmt_2781.column_id = 2781
record_meta_text AS rmt_18474
ON rmt_18474.record_id = r.r_id
AND rmt_18474.column_id = 18474
1 = 1
AND 1 = 1 LIMIT 50