How can I request a random row (or as close to truly random as is possible) in pure SQL?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
See this post: SQL to Select a random row from a database table. It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link):
Select a random row with MySQL:
Select a random row with PostgreSQL:
Select a random row with Microsoft SQL Server:
Select a random row with IBM DB2
Select a random record with Oracle:
In SQL Server you can combine TABLESAMPLE with NEWID() to get pretty good randomness and still have speed. This is especially useful if you really only want 1, or a small number, of rows.
You didn't say which server you're using. In older versions of SQL Server, you can use this:
In SQL Server 2005 and up, you can use
TABLESAMPLE
to get a random sample that's repeatable:For SQL Server 2005 and above, extending @GreyPanther's answer for the cases when
num_value
has not continuous values. This works too for cases when we have not evenly distributed datasets and whennum_value
is not a number but a unique identifier.For SQL Server 2005 and 2008, if we want a random sample of individual rows (from Books Online):