How to randomly select rows in SQL?

2019-01-01 06:36发布

I am using MSSQL Server 2005. In my db, I have a table "customerNames" which has two columns "Id" and "Name" and approx. 1,000 results.

I am creating a functionality where I have to pick 5 customers randomly every time. Can anyone tell me how to create a query which will get random 5 rows (Id, and Name) every time when query is executed?

9条回答
爱死公子算了
2楼-- · 2019-01-01 06:47

Maybe this site will be of assistance.

For those who don't want to click through:

SELECT TOP 1 column FROM table
ORDER BY NEWID()
查看更多
看风景的人
3楼-- · 2019-01-01 06:50

I have found this to work best for big data.

`SELECT TOP 1 Column_Name FROM dbo.Table TABLESAMPLE(1 PERCENT);`

TABLESAMPLE(n ROWS) or TABLESAMPLE(n PERCENT) is random but need to add the TOP n to get the correct sample size.

Using NEWID() is very slow on large tables.

查看更多
看淡一切
4楼-- · 2019-01-01 06:50

If you have a table with millions of rows and care about the performance, this could be a better answer:

SELECT * FROM Table1
WHERE (ABS(CAST(
  (BINARY_CHECKSUM
  (keycol1, NEWID())) as int))
  % 100) < 10

https://msdn.microsoft.com/en-us/library/cc441928.aspx

查看更多
流年柔荑漫光年
5楼-- · 2019-01-01 06:54

SELECT * FROM TABLENAME ORDER BY random() LIMIT 5;

查看更多
残风、尘缘若梦
6楼-- · 2019-01-01 06:55
SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID()
查看更多
公子世无双
7楼-- · 2019-01-01 06:58

In case someone wants a PostgreSQL solution:

select id, name
from customer
order by random()
limit 5;
查看更多
登录 后发表回答