Return rows in random order

SqlSql ServerTsql

Sql Problem Overview


Is it possible to write SQL query that returns table rows in random order every time the query run?

Sql Solutions


Solution 1 - Sql

SELECT * FROM table
ORDER BY NEWID()

Solution 2 - Sql

This is the simplest solution:

SELECT quote FROM quotes ORDER BY RAND() 

Although it is not the most efficient. This one is a better solution.

Solution 3 - Sql

The usual method is to use the NEWID() function, which generates a unique GUID. So,

SELECT * FROM dbo.Foo ORDER BY NEWID();

Solution 4 - Sql

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

Solution 5 - Sql

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

Solution 6 - Sql

SQL Server / MS Access Syntax:

SELECT TOP 1 * FROM table_name ORDER BY RAND()

MySQL Syntax:

SELECT * FROM table_name ORDER BY RAND() LIMIT 1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArsen MkrtchyanView Question on Stackoverflow
Solution 1 - SqlDave BarkerView Answer on Stackoverflow
Solution 2 - SqlAlec SmartView Answer on Stackoverflow
Solution 3 - SqldevstuffView Answer on Stackoverflow
Solution 4 - SqlnilamoView Answer on Stackoverflow
Solution 5 - SqlPinoyDevView Answer on Stackoverflow
Solution 6 - SqlDan BothView Answer on Stackoverflow