How can I select random rows from a SQL Server table?

Neil Pike

January 24, 2000

1 Min Read
ITPro Today logo in a gray background | ITPro Today

A. First you need to generate a random number - this assumes that you have some sort of numeric primary key on the table in the first place. Use something like :-

SELECT @NUM = RAND( (DATEPART(mm, GETDATE()) * 100000 )
+ (DATEPART(ss, GETDATE()) * 1000 )
+ DATEPART(ms, GETDATE()) )

(You could also use another variable like @@IDLE or @@CPU_BUSY to generate "random" numbers)

select @PK = min (col1) + (max (col1) - min (col1)) * @NUM

select * from where col1 = @PK

Another way (courtesy of Joe Celko/Itzik Ben-Gan :-

SELECT S1.key_col
FROM SomeTable AS S1, SomeTable AS S2
WHERE S1.key_col <= S2.key_col
GROUP BY S1.key_col
HAVING COUNT(S2.key_col) =
(SELECT COUNT(*)
FROM SomeTable AS S3) * RAND() + 1;

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like