Conditional Random Order

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
Shendemiar
Forum Contributor
Posts: 404
Joined: Thu Jan 08, 2004 8:28 am

Conditional Random Order

Post by Shendemiar »

Can i order the query so that i would get all of certain value at first, and the all the rest in random order?

Example
AAA, BBB, CCC (Column names and the below are the rows)
2,1,1
2,2,2
2,3,3
1,1,1
1,2,2
1,3,3
3,1,1
3,2,2
3,3,3

And the query would give
1,1,1
1,2,2
1,3,3
And then the rest in random order
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I would probably use a UNION to purposely select the leading ones then randomly select amongst the remaining.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

ORDER BY AAA=1, Rand()

But that doesn't necessarily return
1,1,1
1,2,2
1,3,3
it can also return
1,3,3
1,1,1
1,2,2
It only assures that all records having AAA=1 come before other records.
Post Reply