Monday, May 28, 2012

How choose random records in database by SQL

MS SQL Server:
SELECT TOP 1 Field1, ..., FieldN
FROM Table1
ORDER BY NEWID()

Do not use:
SELECT TOP 1 Field1, ..., FieldN
FROM Table1
ORDER BY RAND()

MS Access:
SELECT TOP 1 Field1 , ..., FieldN
FROM Table1
ORDER BY Rnd(Field1)

Reference:
http://www.carlj.ca/2007/12/16/selecting-random-records-with-sql/

1 comment: