Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

8
  • 38
    -1 for relying on order by rand() or equivalents in all dbs :|. also mentioned here.
    – AD7six
    Commented May 26, 2014 at 9:27
  • 28
    Ten years ago some guy said that using ORDER BY RAND() is wrong...
    – trejder
    Commented Jun 23, 2015 at 6:42
  • 2
    ORDER BY NEWID() seems to be markedly slower on SQL Server. My query looks like: select top 1000 C.CustomerId, CL.LoginName from Customer C inner join LinkedAccount LA on C.CustomerId=LA.CustomerId inner join CustomerLogin CL on C.CustomerId=CL.CustomerId group by C.CustomerId, CL.LoginName having count(*)>1 order by NEWID() Removing the "order by NEWID()" line returns results much faster.
    – Ben Power
    Commented Aug 26, 2015 at 23:02
  • 5
    For SQLite use RANDOM() function. Commented Oct 22, 2015 at 22:34
  • 14
    These solutions don't scale. They are O(n) with n being the number of records in the table. Imagine you have 1 million records, do you really want to generate 1 million random numbers or unique ids? I'd rather use COUNT() and involve that in a new LIMIT expression with a single random number. Commented Oct 2, 2016 at 11:35