quick random row selection in Postgres

2019-01-03 08:51发布

I have a table in postgres that contains couple of millions of rows. I have checked on the internet and I found the following

SELECT myid FROM mytable ORDER BY RANDOM() LIMIT 1;

it works, but it's really slow... is there another way to make that query, or a direct way to select a random row without reading all the table? by the way 'myid' is an integer but it can be an empty field.

thanks

7条回答
甜甜的少女心
2楼-- · 2019-01-03 09:32

You need to use floor:

SELECT myid FROM mytable OFFSET floor(random()*N) LIMIT 1;
查看更多
登录 后发表回答