views:

2062

answers:

3

Is there a succinct way to retrieve a random record from a sql server table?

I would like to randomize my unit test data, so am looking for a simple way to select a random id from a table. In English, the select would be "Select one id from the table where the id is a random number between the lowest id in the table and the highest id in the table."

I can't figure out a way to do it without have to run the query, test for a null value, then re-run if null.

Ideas?

+14  A: 

Yes

SELECT TOP 1 * FROM table ORDER BY NEWID()
Sklivvz
That works, but man, it's slow. There's gotta be a quicker way...
Tom Ritter
It's not slow at all. How many records are we talking about?
Sklivvz
Exactly what I was looking for. I had a feeling it was simpler than I was making it.
Jeremy
Oh, this is elegant!
splattne
You are assuming that NEWID produces pseudorandom values. There is a good chance it will produced sequential values. NEWID just produces unique values. RAND, however, produces pseudo random values.
Skizz
I'm running it on a heavily indexed table with 1,671,145 rows, and it takes 7 seconds to return. The table is pretty optimal too - it's virtually the heart of our database so it's taken care of.
Tom Ritter
@ÂviewAnew. 1.6 million rows and 7 secs on a select that doesn't (and can't) hit an index is not bad.
Sklivvz
@Skizz, rand does not work like that. A SINGLE random value is generated before the SELECT. So if you try "SELECT TOP 10 RAND()... " you always get the same value
Sklivvz
Guess I'm just used to that table always being extremely fast then. Feel free to clean up the comments.
Tom Ritter
A: 

theres a couple of methods here

http://www.brettb.com/SQL_Help_Random_Numbers.asp

Adrian
A: 

Also try your method to get a random Id between MIN(Id) and MAX(Id) and then

SELECT TOP 1 * FROM table WHERE Id >= @yourrandomid

It will always get you one row

Sklivvz
-1, This would only work when there are no missing ID's between min and max. If one is deleted then that same ID is generated by the random function, you will get zero records back.
Neil N