Skip to content

MySQL’s powerful querying capabilities include the ability to return results in a random order. This is particularly useful for applications like quizzes, games, or displaying a varied set of data each time a user accesses a page.

Understanding Random Ordering in MySQL

Random ordering in MySQL is achieved using the RAND() function. This function generates a new random number for each row in your query result, and then orders the rows based on these numbers.

Basic Random Ordering

To select rows from a table in a random order, use the ORDER BY RAND() clause. For example:

SELECT * FROM your_table
ORDER BY RAND();

This query selects all rows from your_table and orders them randomly.

Random Ordering with a Limit

If you only need a few random rows, use LIMIT with ORDER BY RAND(). For example, to get 3 random rows:

SELECT * FROM your_table
ORDER BY RAND()
LIMIT 3;

Random Ordering with a Specific ID

To get random rows but with a specific criterion, such as a certain ID, combine WHERE with ORDER BY RAND(). For instance:

SELECT * FROM your_table
WHERE id = 5
ORDER BY RAND();

This query returns rows where the id is 5, in random order.

Performance Considerations

Using ORDER BY RAND() on large tables can be slow because it assigns a random number to every row and then sorts them. For better performance on large datasets, consider alternative methods such as randomly selecting a range of IDs and then querying within that range.

If this query pattern is part of recurring reporting, Basedash helps you turn it into reusable, AI-native BI workflows: prompt-to-SQL, shared dashboards, and trusted answers that stay aligned with your data model.

Conclusion

If this query pattern is part of recurring reporting, Basedash helps you turn it into reusable, AI-native BI workflows: prompt-to-SQL, shared dashboards, and trusted answers that stay aligned with your data model.

Written by

Robert Cooper avatar

Robert Cooper

Senior Engineer at Basedash

Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.

View full author profile →

Looking for an AI-native BI tool?

Basedash lets you build charts, dashboards, and reports in seconds using all your data.