[Solved] How is using Join faster than using just Rand() in MySQL

EverSQL Database Performance Knowledge Base

How is using Join faster than using just Rand() in MySQL

Database type:

How is

SELECT t.id 
FROM table t 
JOIN (SELECT(FLOOR(max(id) * rand())) AS maxid FROM table) 
AS tt 
ON t.id >= tt.maxid 
LIMIT 1

faster than

SELECT * FROM `table` ORDER BY RAND() LIMIT 1

I am actually having trouble understanding the first. Maybe if I knew why one is faster than the other I would have a better understanding.

*original post @ Difficult MySQL self-join please explain

How to optimize this SQL query?

The following recommendations will help you in your 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 Subqueries (query line: 4): 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.
  2. Avoid Subqueries (query line: 10): 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.
  3. Sort and Limit Before Joining (modified query below): In cases where the joins aren't filtering any rows, it's possible to sort and limit the amount of rows using a subquery in the FROM clause, before applying the joins to all other tables.
The optimized query:
SELECT
        t_id 
    FROM
        (SELECT
            t.id AS t_id 
        FROM
            table t LIMIT 1) t 
    JOIN
        (
            SELECT
                (FLOOR(max(table.id) * rand())) AS maxid 
            FROM
                table
        ) AS tt 
            ON t.t_id >= tt.maxid LIMIT 1

Related Articles



* original question posted on StackOverflow here.