How to request a random row in SQL?

前端 未结 29 2912
孤城傲影
孤城傲影 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:27

    Best way is putting a random value in a new column just for that purpose, and using something like this (pseude code + SQL):

    randomNo = random()
    execSql("SELECT TOP 1 * FROM MyTable WHERE MyTable.Randomness > $randomNo")
    

    This is the solution employed by the MediaWiki code. Of course, there is some bias against smaller values, but they found that it was sufficient to wrap the random value around to zero when no rows are fetched.

    newid() solution may require a full table scan so that each row can be assigned a new guid, which will be much less performant.

    rand() solution may not work at all (i.e. with MSSQL) because the function will be evaluated just once, and every row will be assigned the same "random" number.

提交回复
热议问题