How to request a random row in SQL?

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

    In late, but got here via Google, so for the sake of posterity, I'll add an alternative solution.

    Another approach is to use TOP twice, with alternating orders. I don't know if it is "pure SQL", because it uses a variable in the TOP, but it works in SQL Server 2008. Here's an example I use against a table of dictionary words, if I want a random word.

    SELECT TOP 1
      word
    FROM (
      SELECT TOP(@idx)
        word 
      FROM
        dbo.DictionaryAbridged WITH(NOLOCK)
      ORDER BY
        word DESC
    ) AS D
    ORDER BY
      word ASC
    

    Of course, @idx is some randomly-generated integer that ranges from 1 to COUNT(*) on the target table, inclusively. If your column is indexed, you'll benefit from it too. Another advantage is that you can use it in a function, since NEWID() is disallowed.

    Lastly, the above query runs in about 1/10 of the exec time of a NEWID()-type of query on the same table. YYMV.

提交回复
热议问题