How to request a random row in SQL?

前端 未结 29 3490
孤城傲影
孤城傲影 2020-11-21 06:45

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

29条回答
  •  庸人自扰
    2020-11-21 07:08

    With SQL Server 2012+ you can use the OFFSET FETCH query to do this for a single random row

    select  * from MyTable ORDER BY id OFFSET n ROW FETCH NEXT 1 ROWS ONLY
    

    where id is an identity column, and n is the row you want - calculated as a random number between 0 and count()-1 of the table (offset 0 is the first row after all)

    This works with holes in the table data, as long as you have an index to work with for the ORDER BY clause. Its also very good for the randomness - as you work that out yourself to pass in but the niggles in other methods are not present. In addition the performance is pretty good, on a smaller dataset it holds up well, though I've not tried serious performance tests against several million rows.

提交回复
热议问题