Question

I have a column name unique and Im trying to print results ordered randomly, first all the rows which starts with lead_ and then all the rest of the rows.

For example if I have this rows:

abc
lead_ass
dsff
dds
lead_fdg
fds
lead_hhf

I need to first print lead_ass,lead_fdg,lead_nhf ordered randomly and then all the rest, also ordered randomly.

Was it helpful?

Solution

You can do this as:

order by (col like 'lead_%') desc,
         rand()

The expression (col like 'lead_%') returns either true (treated as 1) or false (treated as 0), so the desc puts the matches first. The rand() is just because you say you want things ordered randomly. This will order both groups randomly.

OTHER TIPS

You can use CASE and LEFT function

ORDER BY CASE 
         WHEN LEFT(col,5) ='lead_' 
         THEN 1 ELSE 2
         END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top