← Back to Blog
[DB] How to select random rows from a table

[DB] How to select random rows from a table

It is needed to select some records randomly to take sample data from a table. MySQL can accomplish this task by using rand() function in order by clause as below.

In case selecting 20 users randomly.

SELECT * FROM users ORDER BY rand() LIMIT 20

In case it has to be ordered by name

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