Random Select in MySQL
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
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.
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.
SELECT * FROM your_table ORDER BY RAND();
This query selects all rows from your_table and orders them randomly.
Often, you may want to limit the number of rows returned in a random selection.
SELECT * FROM your_table ORDER BY RAND() LIMIT 5;
This retrieves 5 random rows from your_table.
Using RAND() with large datasets can be inefficient because it requires a full table scan.
For more efficient random selections in large tables, consider the following approach:
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.
You can also combine RAND() with WHERE clauses for conditional random sampling.
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.
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
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.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.