In this tip, you will learn various techniques to select random items from a database table in MySQL.
MySQL does not have any automatic way to select random items from a database table. In some programming tasks, it is required and very useful to select random items from a result set such as:
MySQL does not have any automatic way to select random items from a database table. In some programming tasks, it is required and very useful to select random items from a result set such as:
- You'll need to select a random picture to display it for a category, so each time when the visitor come to your website, they will see different pictures displaying on the categories.
- You'll need to select a random banner to display to visitors.
- You'll need to pick a row in "quote of the day" application.
- And more and more cases you can think of...
SELECT * FROM table ORDER BY RAND() LIMIT 1The key technique used above is randomizing the returned records and then pick the first one. If you want to select n random items just change the parameter after LIMIT as follows:
SELECT * FROM table ORDER BY RAND() LIMIT nThe technique as demonstrated above work very well with the small table. With the table which has many records, it could be very slow because we have to sort the entire table to pick random items. To work around this problem, we will use another technique as demonstrated below:
- First we select a random ID(s) of a column. This column should be the primary key and the value is in sequential range.
- Then pick the rows based on the ID(s) we selected
SET @ID = FLOOR(RAND( )* N) + 1; SELECT * FROM table WHERE ID >= @ID LIMIT 1This technique work faster because the ID column is indexed and we don't have to order the whole table as previous one.

No Response to "Select Random Records in Database Table"
Post a Comment