[Solved] Optimise MySQL ORDER BY RAND() on a filtered GROUP BY query to avoid temp/indexless join

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:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. 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
  2. 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.
  3. 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.
  4. 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.
  5. 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:
            count(u.prodid) AS count 
            usage u 
            optimizedSub1.p_prodid = u.prodid LIMIT 1) AS count 
            p.prodid AS p_prodid 
            prods p 
            p.ownerid > 0 
            AND p.active = 1 
        ORDER BY
            rand() LIMIT 1) AS optimizedSub1

Related Articles

* original question posted on StackOverflow here.