DEV Community

Cover image for MariaDB Quick-tip #2 - Randomize rows
Allan Simonsen
Allan Simonsen

Posted on

MariaDB Quick-tip #2 - Randomize rows

MariaDB tips and tricks

This is part of a series of quick tips and tricks I have accumulated over the year, that I think can be useful for others.
If you have similar short tips and tricks please leave a comment.

Randomize rows

Sometimes you want the returned rows of your query to be randomized. That could be when generating test data.
The trick is to use ORDER BY RAND(). The RAND() function will generate a new random number between 0 and 1 for each row and when sorted the rows will be randomized.
This is not something you should put into your production code unless you have no other way of randomizing you rows, because MariaDB has no way of optimizing this kind of query so if the trick is used on a large table it will take time and computing resources.
This approach to randomize the rows of your query is only slightly different from how you would achieve the same result on the SQL Server

CREATE OR REPLACE TEMPORARY TABLE names (Name VARCHAR(50));

INSERT INTO names (Name) 
VALUES ('Joe'), ('Bob'), ('Anne'), ('Jane');

SELECT Name
  FROM names
 ORDER BY RAND() -- Ordering by RAND() will randomized the rows
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)