My query selects results correctly using ORDER BY CASE.
I would like to randomize the results within EACH case. i.e.
ORDER BY CASE WHEN apples (randomize) THEN 1 WHEN pears (randomize) THEN 2, etc.
So my results are still ordered by each case but within the results PER case they are random, each time the query is run.
views:
36answers:
2
A:
You can try ORDER BY CASE, RAND()
. RAND()
generates a random number, of course.
However, I heard somewhere that shuffling elements in SQL is not quite the most efficient way and it is better to randomize elements in PHP. But randomizing them per case is not a trivial task. (PHP rand()
function)
phimuemue
2010-06-19 11:20:57
I believe there is an issue with using RAND to sort in MySQL when the result set is large, but I am not 100% certain.
Phil Wallach
2010-06-19 11:44:34
Yes there is: http://jan.kneschke.de/projects/mysql/order-by-rand/
ircmaxell
2010-06-19 11:57:39
this does work however - after the case, 'when', 'then' and END, RAND() - finishes the query off perfectly.
InnateDev
2010-06-19 15:22:21
A:
Often times for simplicity I will throw a NewID() function into a SQL Order By to randomize the order of the results. In your case, you could use the uniqid(), or if you really are passing the query straight to MSSQL, you could use NEWID() as well...
fdfrye
2010-06-19 11:43:17