DEV Community

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

Posted on

2 1

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay