Wednesday, November 3, 2010

MS SQL Fast SELECT a Random Row

Found this bit of code for MS SQL to quickly SELECT a random row from a table of millions of records.

SELECT TOP 1 *
FROM table_name
WHERE Primary_Key_ID = (SELECT CEILING(MAX(Primary_Key_ID) * RAND())
FROM table_name)

This is faster than the usual ORDER BY NEWID() as this method creates a temporary table (or view) with an additional column of NewIDs

The downside is that, if you have gaps in your Primary Key, you should take care of the statement returning blank rows in your code.