tags:

views:

1827

answers:

2

How do we combine http://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql and http://stackoverflow.com/questions/183124/multiple-random-values-in-sql-server-2005 to select N random rows using a single pure-SQL query? Ideally, I'd like to avoid the use of stored procedures if possible. Is this even possible?

CLARIFICATIONS:

  1. Pure SQL refers to as close as possible to the ANSI/ISO standard.
  2. The solution should be "efficient enough". Granted ORDER BY RAND() might work but as others have pointed out this isn't feasible for medium-sized tables.
+3  A: 

The answer to your question is in the second link there:

SELECT * FROM table ORDER BY RAND() LIMIT 1

Just change the limit, and/or rewrite for SQL Server:

SELECT TOP 1 * FROM table ORDER BY newid()

Now, this strictly answers your question, but you really shouldn't be using this solution. Just try it on a large table and you'll see what I mean.

If your key-space is sequential, either without holes, or with very few holes, and if it has very few holes, you're not too concerned that some rows have a slightly higher chance of being picked than others, then you can use a variation where you calculate which key you want to retrieve randomly, ranging from 1 to the highest key in your table, and then retrieve the first row that has a key equal to or higher than the number you calculated. You only need the "higher than" part if your key-space has holes.

This SQL is left as an excercise for the reader.


Edit: Note, a comment to another answer here mentions that perhaps pure SQL means ANSI standard SQL. If that is the case, then there is no way, since there is no standardized random function, nor does every database engine treat the random number function the same way. At least one engine I've seen "optimizes" the call by calling it once and just repeating the calculated value for all rows.

Lasse V. Karlsen
NEWID() is a bad idea if you want truly random samples, GUIDs have a lot of structure. If you don't care about being really random though, go ahead.
A: 

I don't know about pure ANSI, and it's not simple, but you can check out my answer to a similar question here: http://stackoverflow.com/questions/249301/simple-random-samples-from-a-mysql-database

It's not clear to me how to implement what you propose if assumption #3 is false (that is, your table has holes).
Gili
You have to rewrite the whole table so assumption #3 is true, so it's a very slow O(n) operation. Create a new table with the same columns as the original table, and also an identity column for a new primary key that will have no gaps. Then insert the whole original table into the new one.