How to request a random row in SQL?

2018-12-31 01:44发布

How can I request a random row (or as close to truly random as is possible) in pure SQL?

标签: sql random
28条回答
初与友歌
2楼-- · 2018-12-31 02:16

There is better solution for Oracle instead of using dbms_random.value, while it requires full scan to order rows by dbms_random.value and it is quite slow for large tables.

Use this instead:

SELECT *
FROM employee sample(1)
WHERE rownum=1
查看更多
无色无味的生活
3楼-- · 2018-12-31 02:18
ORDER BY NEWID()

takes 7.4 milliseconds

WHERE num_value >= RAND() * (SELECT MAX(num_value) FROM table)

takes 0.0065 milliseconds!

I will definitely go with latter method.

查看更多
只若初见
4楼-- · 2018-12-31 02:18

In MSSQL (tested on 11.0.5569) using

SELECT TOP 100 * FROM employee ORDER BY CRYPT_GEN_RANDOM(10)

is significantly faster than

SELECT TOP 100 * FROM employee ORDER BY NEWID()
查看更多
美炸的是我
5楼-- · 2018-12-31 02:18

I have to agree with CD-MaN: Using "ORDER BY RAND()" will work nicely for small tables or when you do your SELECT only a few times.

I also use the "num_value >= RAND() * ..." technique, and if I really want to have random results I have a special "random" column in the table that I update once a day or so. That single UPDATE run will take some time (especially because you'll have to have an index on that column), but it's much faster than creating random numbers for every row each time the select is run.

查看更多
泛滥B
6楼-- · 2018-12-31 02:18

A simple and efficient way from http://akinas.com/pages/en/blog/mysql_random_row/

SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;
查看更多
步步皆殇っ
7楼-- · 2018-12-31 02:18

For Firebird:

Select FIRST 1 column from table ORDER BY RAND()
查看更多
登录 后发表回答