mysqldude

Returning random row

Version compatibility

StepMySQLMariaDB
5.65.78.08.4910.610.1111.411.8
WHERE col2 >= FLOOR(MAX(col2) * RAND()) ORDER BY col2 LIMIT 1 (original)
original post
✓✓✓✓✓✓✓✓✓
ORDER BY RAND() LIMIT 1 (uniform, fine for small tables)
modern rewrite
✓✓✓✓✓✓✓✓✓
WHERE col2 >= FLOOR(MAX(col2) * RAND()) ORDER BY col2 LIMIT 1 (original) original post
MySQL 5.6✓5.7✓8.0✓8.4✓9✓
MariaDB 10.6✓10.11✓11.4✓11.8✓
ORDER BY RAND() LIMIT 1 (uniform, fine for small tables) modern rewrite
MySQL 5.6✓5.7✓8.0✓8.4✓9✓
MariaDB 10.6✓10.11✓11.4✓11.8✓
✓works ✓ 1062fails with the error the step demonstrates ⚠works with a warning ≠runs, result differs ✗fails Tested 2026-11-25 on 5.6.51, 5.7.44, 8.0.46, 8.4.13, 9.7.4, 10.6.28, 10.11.19, 11.4.13, 11.8.9

The original article

First published 2012-05-08. The text below is the original; the table above shows how it behaves on current versions.

This is mini example of how to return a random row from your table:

mysql> select * from t1;
+--------+------+------+
| col1   | col2 | col3 |
+--------+------+------+
| ronan4 |  100 |  115 |
| ronan4 |  155 |  116 |
| ronan4 |  225 |  250 |
| ronan4 |  300 |  275 |
| ronan4 |  325 |  350 |
| ronan4 |    1 |    2 |
| ronan4 |    1 |    3 |
| t13    |    7 |    6 |
+--------+------+------+
8 rows in set (0.00 sec)

Col2 is a primary or unique key to the table. If we issue the following statement:

mysql> select * from t1 where col2 >= (select floor(max(col2) * rand()) from t1)
    -> order by col2
    -> limit 1;
+--------+------+------+
| col1   | col2 | col3 |
+--------+------+------+
| ronan4 |    1 |    3 |
+--------+------+------+
1 row in set (0.01 sec)

mysql> select * from t1 where col2 >= (select floor(max(col2) * rand()) from t1) order by col2 limit 1;
+--------+------+------+
| col1   | col2 | col3 |
+--------+------+------+
| ronan4 |  155 |  116 |
+--------+------+------+
1 row in set (0.01 sec)

mysql> select * from t1 where col2 >= (select floor(max(col2) * rand()) from t1) order by col2 limit 1;
+--------+------+------+
| col1   | col2 | col3 |
+--------+------+------+
| ronan4 |    1 |    2 |
+--------+------+------+
1 row in set (0.00 sec)

mysql> select * from t1 where col2 >= (select floor(max(col2) * rand()) from t1) order by col2 limit 1;
+--------+------+------+
| col1   | col2 | col3 |
+--------+------+------+
| ronan4 |  100 |  115 |
+--------+------+------+
1 row in set (0.00 sec)

mysql> select * from t1 where col2 >= (select floor(max(col2) * rand()) from t1) order by col2 limit 1;
+--------+------+------+
| col1   | col2 | col3 |
+--------+------+------+
| ronan4 |  225 |  250 |
+--------+------+------+
1 row in set (0.00 sec)

Issuing the statement several times show different results each time. [googleplus]