Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort ENUM column in MySQL database?

I have color column in MySQL table which type is ENUM('RED', 'YELLOW', 'MY_COLOR', 'BLACK'), and another name column which type is VARCHAR(30).

I would like to get all table rows in the following order:

  • YELLOW rows first, sorted by name
  • RED rows last, sorted by name
  • In the middle, all other rows, sorted by name

Is that possible to make this kind of sort in 1 query ?

like image 201
Misha Moroshko Avatar asked Oct 19 '10 03:10

Misha Moroshko


People also ask

How do I sort a column in MySQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can we sort enum?

If you just create a list of the enum values (instead of strings) via parsing, then sort that list using Collections. sort , it should sort the way you want. If you need a list of strings again, you can just convert back by calling name() on each element.

How can I get enum possible values in a MySQL database?

$syntax = mysql_query("SELECT COLUMN_TYPY FROM information_schema. `COLUMNS` WHERE TABLE_NAME = '$table' AND COLUMN_NAME ='$colm'"); if (! mysql_error()){ //Get a array possible values from table and colm.


2 Answers

Use:

ORDER BY CASE color
           WHEN 'YELLOW' THEN 1
           WHEN 'RED' THEN 3
           ELSE 2
         END, name 
like image 125
OMG Ponies Avatar answered Oct 06 '22 16:10

OMG Ponies


This works fine with mysql. But for h2 DB it throws an error

Caused by: org.h2.jdbc.JdbcSQLException: Order by expression "CASEWHEN((color = 'YELLOW'), 1, CASEWHEN((color = 'RED'),3))" must be in the result list in this case; SQL statement:

To avoid the error add the stmt CASEWHEN((color = 'YELLOW'), 1, CASEWHEN((color = 'RED'),3)) in the select clause.

like image 25
Manu Avatar answered Oct 06 '22 15:10

Manu