Home > Article > Backend Development > How to randomly select n records or randomly sort the records? _PHP Tutorial
Q. How to get randomly sorted results?
A. To get randomly sorted columns, or to return x randomly selected columns, you can use random numbers. But the RAND function can only return one result in a query. You can do ORDER BY on the column returned by the NOWID function. Please see the example:
SELECT *
FROM Northwind..Orders
ORDER BY NEWID()
SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()
It was really difficult to translate this passage, so I just ignored the original text and just translated it directly.
However, I would like to remind everyone that this method requires scanning the entire table, then generating a calculated column and then sorting it. It is best not to do such an operation on a large table, otherwise it will be very 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()
—SQL Server MVPs