Select Random Records in MySQL
Sorting records in SQL is not a problem thanks to the ORDER BY statement.
However, if you do not want to sort the data by a certain column, but instead want to query the data records every time in a new, random order, you can pass the MySQL function RAND() to the ORDER BY clause.
Example over an entire table:
1 2 3 |
SELECT * FROM mytable ORDER BY RAND(); |
Select n Random Rows in SQL
Example that returns a certain number of records:
1 2 3 |
SELECT * FROM mytable ORDER BY RAND() LIMIT 5; |
In this example, five random records are fetched from the table. The LIMIT statement was used for this.