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?
Maybe this site will be of assistance.
For those who don't want to click through:
I have found this to work best for big data.
TABLESAMPLE(n ROWS) or TABLESAMPLE(n PERCENT)
is random but need to add theTOP n
to get the correct sample size.Using
NEWID()
is very slow on large tables.If you have a table with millions of rows and care about the performance, this could be a better answer:
https://msdn.microsoft.com/en-us/library/cc441928.aspx
SELECT * FROM TABLENAME ORDER BY random() LIMIT 5;
In case someone wants a PostgreSQL solution: