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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay