How to request a random row in SQL?

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

    As pointed out in @BillKarwin's comment on @cnu's answer...

    When combining with a LIMIT, I've found that it performs much better (at least with PostgreSQL 9.1) to JOIN with a random ordering rather than to directly order the actual rows: e.g.

    SELECT * FROM tbl_post AS t
    JOIN ...
    JOIN ( SELECT id, CAST(-2147483648 * RANDOM() AS integer) AS rand
           FROM tbl_post
           WHERE create_time >= 1349928000
         ) r ON r.id = t.id
    WHERE create_time >= 1349928000 AND ...
    ORDER BY r.rand
    LIMIT 100
    

    Just make sure that the 'r' generates a 'rand' value for every possible key value in the complex query which is joined with it but still limit the number of rows of 'r' where possible.

    The CAST as Integer is especially helpful for PostgreSQL 9.2 which has specific sort optimisation for integer and single precision floating types.

提交回复
热议问题