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 OFFSET In LIMIT Clause (query line: 38): OFFSET clauses can be very slow when used with high offsets (e.g. with high page numbers when implementing paging). Instead, use the following \u003ca target\u003d"_blank" href\u003d"http://www.eversql.com/faster-pagination-in-mysql-why-order-by-with-limit-and-offset-is-slow/"\u003eseek method\u003c/a\u003e, which provides better and more stable response rates.
- 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.
- Replace In Subquery With Correlated Exists (modified query below): In many cases, an EXISTS subquery with a correlated condition will perform better than a non correlated IN subquery.
Optimal indexes for this query:
ALTER TABLE `tbl_activities` ADD INDEX `tbl_activities_idx_user_id` (`user_id`);
ALTER TABLE `tbl_subscriptions` ADD INDEX `tbl_subscriptions_idx_subscriber_id_subscribed_uid` (`subscriber_id`,`subscribed_uid`);
ALTER TABLE `tbl_users` ADD INDEX `tbl_users_idx_id` (`id`);
The optimized query:
ON act.user_id = u.id
NOT EXISTS (
ON s.subscribed_uid = u1.id
s.subscriber_id = 1
u.id = s.subscribed_uid
COUNT(act.user_id) DESC LIMIT 0,
15) AS t
tbl_users.id = t.user_id