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 Ordering by Random Function (query line: 19): Ordering by RAND will cause performance degradation as the data grows. An alternative to fetch one random result is to pick a random number in the application and 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
- Avoid Selecting Unnecessary Columns (query line: 11): 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.
- Reduce Impact Of Subqueries In Select Clause (modified query below): Subqueries in the SELECT clause will be executed once per each select row. Therefore, reducing the amount of selected rows in the FROM clause before getting to the SELECT clause will result in a performance improvement.
- Replace Left Join With Subquery (modified query below): The pattern of inflating the amount of data (using joins) and deflating (using GROUP BY) usually slows down queries. In this case, it can be avoided by moving some of the logic to the SELECT clause, and therefore removing some of the LEFT JOINs. In some cases, this transformation can lead to an obsolete GROUP BY clause, which can also be removed.
Optimal indexes for this query:
ALTER TABLE `prods` ADD INDEX `prods_idx_active_ownerid` (`active`,`ownerid`);
ALTER TABLE `usage` ADD INDEX `usage_idx_prodid` (`prodid`);
The optimized query:
SELECT
optimizedSub1.*,
(SELECT
count(u.prodid) AS count
FROM
usage u
WHERE
optimizedSub1.p_prodid = u.prodid LIMIT 1) AS count
FROM
(SELECT
p.*,
p.prodid AS p_prodid
FROM
prods p
WHERE
p.ownerid > 0
AND p.active = 1
ORDER BY
rand() LIMIT 1) AS optimizedSub1