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 Correlated Subqueries In Select Clause (modified query below): The aggregation function located in a subquery inside the SELECT clause, is executed once for every matched row. Extracting this subquery to a temporary table will improve performance significantly.
- 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.
- 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.
- 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'.
- Use UNION ALL instead of UNION (query line: 16): Always use UNION ALL unless you need to eliminate duplicate records. By using UNION ALL, you'll avoid the expensive distinct operation the database applies when using a UNION clause.
Optimal indexes for this query:
ALTER TABLE `es_temp1` ADD INDEX `es_temp1_idx_user_id` (`user_id`);
ALTER TABLE `es_temp2` ADD INDEX `es_temp2_idx_user_id` (`user_id`);
ALTER TABLE `users` ADD INDEX `users_idx_id` (`id`);
The optimized query:
SELECT
u.*,
r.shop_id,
es_temp1.num_reservations,
es_temp2.num_orders
FROM
users u
INNER JOIN
(
SELECT
r.user_id,
r.shop_id
FROM
reservations r
UNION
SELECT
so.user_id,
so.shop_id
FROM
shop_orders so
) AS r
ON u.id = r.user_id
LEFT JOIN
es_temp1
ON es_temp1.user_id = u.id
LEFT JOIN
es_temp2
ON es_temp2.user_id = u.id
GROUP BY
u.id
ORDER BY
NULL