How to request a random row in SQL?

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

    Didn't quite see this variation in the answers yet. I had an additional constraint where I needed, given an initial seed, to select the same set of rows each time.

    For MS SQL:

    Minimum example:

    select top 10 percent *
    from table_name
    order by rand(checksum(*))
    

    Normalized execution time: 1.00

    NewId() example:

    select top 10 percent *
    from table_name
    order by newid()
    

    Normalized execution time: 1.02

    NewId() is insignificantly slower than rand(checksum(*)), so you may not want to use it against large record sets.

    Selection with Initial Seed:

    declare @seed int
    set @seed = Year(getdate()) * month(getdate()) /* any other initial seed here */
    
    select top 10 percent *
    from table_name
    order by rand(checksum(*) % seed) /* any other math function here */
    

    If you need to select the same set given a seed, this seems to work.

提交回复
热议问题