MySQL ORDER BY rand(), name ASC MySQL ORDER BY rand(), name ASC database database

MySQL ORDER BY rand(), name ASC


Use a subquery:

SELECT * FROM (    SELECT * FROM users ORDER BY rand() LIMIT 20) T1ORDER BY name 

The inner query selects 20 users at random and the outer query orders the selected users by name.


Beware of ORDER BY RAND() because of performance and results. Check this article out: http://jan.kneschke.de/projects/mysql/order-by-rand/


Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.

SELECT COUNT(id) FROM users; #id is the primary key

Then, get a random twenty rows.

$start_row = mt_rand(0, $total_rows - 20);

The final query:

SELECT * FROM users ORDER BY name ASC LIMIT $start_row, 20;