Skip to content

In MySQL, selecting rows in a random order can be useful for things like displaying random records to users or conducting random sampling of data. This guide explains how to perform a random select in MySQL.

Understanding the RAND() Function

The primary method for achieving random selection in MySQL is through the RAND() function. This function generates a random floating-point value between 0 and 1. When used in a SELECT query, it can randomize the order of the result set.

Example of RAND() in Action

SELECT * FROM your_table ORDER BY RAND();

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

Limiting Random Selections

Often, you may want to limit the number of rows returned in a random selection.

Example with a LIMIT Clause

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

This retrieves 5 random rows from your_table.

Performance Considerations

Using RAND() with large datasets can be inefficient because it requires a full table scan.

Efficient Random Selections

For more efficient random selections in large tables, consider the following approach:

Using a Random Row Offset

SET @row_count = (SELECT COUNT(*) FROM your_table);
SET @offset = FLOOR(RAND() * @row_count);
PREPARE STMT FROM 'SELECT * FROM your_table LIMIT 1 OFFSET ?';
EXECUTE STMT USING @offset;

This method calculates a random offset and retrieves a single row from that position.

Random Sampling with WHERE Clauses

You can also combine RAND() with WHERE clauses for conditional random sampling.

Example with a WHERE Clause

SELECT * FROM your_table WHERE your_condition ORDER BY RAND() LIMIT 10;

This query selects a random sample of 10 rows that meet your_condition.

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.