13 Votes

MySQL: Select random record from table

Tip by PC Control | 2012-07-30 at 19:16

Sometimes you want to get a random record from a MySQL database. For this purpose we can simply use the following simple query:

SELECT * FROM tab ORDER BY RAND() LIMIT 1

The idea is this: We sort our result by chance and limit our records returned to 1. Thus, exactly one data set is returned by chance.

If we still want to consider other criteria for our random data set, we can still insert any WHERE clause we want:

SELECT * FROM tab WHERE id<100 ORDER BY RAND() LIMIT 1

In this example, we are looking for a random record out of all records that have an id less than 100. Likewise we could make any other arbitrary WHERE clause to restrict our results.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.