How do I randomly select n records or sort records randomly? Q. How do I get the random sorting result?
A. You can use random numbers to obtain columns in random sorting or return x randomly selected columns. However, the RAND function can return only one result in a query. You can create order by on the columns returned BY the NOWID function. See the example:
SELECT *
FROM Northwind... Orders
Order by newid ()
Select top 10 *
FROM Northwind... Orders
Order by newid ()
This article is really difficult to translate. it is simply a free translation of the original text.
However, it should be noted that this method scans the entire table and generates a computed column for sorting. it is best not to perform such operations on large tables, otherwise it will be slow.
Q. How can I randomly sort query results?
A. to randomly order rows, or to return x number of randomly chosen rows, you can use the RAND function inside the SELECT statement. but the RAND function is resolved only once for the entire query, so every row will get same value. you can use an order by clause to sort the rows by the result from the NEWID function, as the following code shows:
SELECT *
FROM Northwind... Orders
Order by newid ()
Select top 10 *
FROM Northwind... Orders
Order by newid ()