The ability to select random records from a table in MySQL can be helpful. Luckily this is easy to do with the RAND()
function.
RAND()
returns a random floating point value between 0 and 1. You can select random records in MySQL by using the RAND()
function together with ORDER
and LIMIT
clauses. Here is an example:
mysql> SELECT * FROM sample_data ORDER BY RAND() LIMIT 10;
+------+------------+-----------+------------------------------+-------------+-----------------+
| id | first_name | last_name | email | country | ip_address |
+------+------------+-----------+------------------------------+-------------+-----------------+
| 748 | Deborah | Baker | [email protected] | Russia | 136.251.75.108 |
| 569 | Juan | Reid | [email protected] | Indonesia | 109.164.128.38 |
| 504 | Bonnie | Reynolds | [email protected] | Japan | 236.192.249.208 |
| 816 | Jack | Larson | [email protected] | Indonesia | 242.121.191.69 |
| 204 | Gary | Simmons | [email protected] | Australia | 49.74.61.181 |
| 477 | Brenda | Stephens | [email protected] | Paraguay | 215.16.171.113 |
| 542 | Donna | Morris | [email protected] | Philippines | 157.138.222.124 |
| 523 | Shirley | Cox | [email protected] | Brazil | 81.117.80.15 |
| 119 | Carlos | Jackson | [email protected] | Samoa | 155.210.120.247 |
| 764 | Paula | Brooks | [email protected] | Denmark | 106.81.107.200 |
+------+------------+-----------+------------------------------+-------------+-----------------+
Since RAND()
will return a random number, sorting the data by RAND() will shuffle the records that are output (values in the id
column above are generally returned in ascending order). Using LIMIT
will determine how many records to return in your query.