MySQL, Software Development

How to List a Specific number of Random Rows in MySQL

Suppose we have a use case to order the number of rows in MySQL randomly. How can we do it? Assume we have a list of 5 items you want to display, but these items are randomly chosen items. In MySQL, you use the rand() function in the ORDER BY clause.

Software Environment For MySQL

This post uses the following items. To create a MySQL Docker container, please follow the Docker Compose for MySQL For Local Development.

  • Windows 10
  • MySQL 8 Docker image

The SQL Statement With Random Rows

Suppose we have the following MySQL table with only five rows. But we have a requirement to display random rows coming from MySQL.

We can display the rows randomly by using and tweaking the ORDER BY clause. Moreover, we use the rand function with the ORDER BY clause.

Every time we run the MySQL command, we get the same rows but in random order. For example, we get the following on the first run.

Next, we get the following on the second run.

Then, on the third run, we get yet another different result.

Note that when others run the same MySQL command, their random rows may vary from the results of this post.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like