For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
The optimization process and recommendations:
- Avoid Subqueries (query line: 20): 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.
- 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'.
- Prefer Sorting/Grouping By The First Table In Join Order (modified query below): The database can use indexes more efficiently when sorting and grouping using columns from the first table in the join order. The first table is determined based on the prediction of the the optimal first table, and is not necessarily the first table shown in the FROM clause.
Optimal indexes for this query:
ALTER TABLE `product` ADD INDEX `product_idx_id` (`id`);
ALTER TABLE `purchases_log` ADD INDEX `purchases_log_idx_store_id` (`store_id`);
ALTER TABLE `purchases_log` ADD INDEX `purchases_log_idx_user_id` (`user_id`);
ALTER TABLE `user` ADD INDEX `user_idx_id` (`id`);
The optimized query:
ON pl.user_id = u.id
ON pl.product_id = p.id
ON u.id = t1.user_id
pl.store_id IN (
1, 2, 3
AND occurrences > 1