Often in many situations during programming you might need to pull randomly selected records from a MySQL Database. For example displaying 5 randomly selected ads in your site. All that is needed is use rand() function.
SELECT ID FROM
ORDER BY RAND() LIMIT 5
Make sure you use the LIMIT clause as otherwise it would cause an overhead in the results. Note that if you use rand() function in a database with large number of records, the query would slowdown. So make sure you filter the necessary records and then apply rand() to pull out randomly selected records from the database.
- Optimizing MySQL Rand() against Slowdowns
- Retrieve select box value from database using PHP
- MySQL delete is very slow and takes long time!
- how to store and retrieve checkbox value in php?
- Mysql Query – Use brackets for multiple conditions!
- How to manually upgrade wordpress from older versions
- WordPress – how to add custom field when post is published?
- WordPress – How to save default values in theme options page?
- MySQL database without primary key is too slow!