Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL ORDER BY [custom SET field value]

I hope there's a simple solution for this:

I have a table where each row has it's own status (SET type field). Statuses can be:

  • offline
  • available
  • busy
  • distance

I'd like to order as follows

  • available
  • busy
  • distance
  • offline

I thought a simple

ORDER BY `status` ASC

will do the trick (alphabetical order) but it gives me the following:

  • offline
  • available
  • busy
  • distance

How can is sort out this in the most simple way?

Thanks in advance,

fabrik

like image 697
fabrik Avatar asked Oct 26 '10 16:10

fabrik


People also ask

How do you ORDER BY field?

select type , COUNT from TABLE order by FIELD(type,'A','B','C','D') ; It works fine if the column type has value for 'A,B,C,D' . In some cases the order by FIELD('A','B','C','D') some columns may not have value in table . In this cases I want to put 0 for it and construct a result .

How do I change the order of data in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.


3 Answers

SELECT * FROM table ORDER BY FIELD(status,'offline','available','busy','distance')

see Mysql order by specific ID values

like image 180
Cedric Avatar answered Nov 15 '22 10:11

Cedric


Thought I'd add another way to order by custom field values,

ORDER BY FIND_IN_SET(status, 'available,busy,distance,offline')

(If the given strings contain a quote simply escape it)

like image 45
MSpreij Avatar answered Nov 15 '22 10:11

MSpreij


You could also do something like this, if reordering the SET values in impractical:

... ORDER BY CASE `status` 
                WHEN 'available' THEN 1
                WHEN 'busy' THEN 2
                WHEN 'distance' THEN 3
                WHEN 'offline' THEN 4
             END
like image 37
Daniel Vassallo Avatar answered Nov 15 '22 09:11

Daniel Vassallo