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.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
MySQL: Delete Data from Table - Difference between TRUNCATE, DELETE and DROP
Tutorial | 0 Comments
MySQL: Display search results on multiple pages
Tutorial | 0 Comments
MySQL: Add or Insert Random Number
Tip | 0 Comments
MySQL: Add new Column to a Table
Tutorial | 0 Comments
MySQL: 3 Ways of showing Table Definition and Structure
Info | 0 Comments
SQLite: Creating an Index on one or more Columns
Info | 0 Comments
SQLite: Check whether Table exists
Info | 0 Comments
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.