In another question, someone asks how to do custom sorting in MySQL. They give the following example dataset:
ID Language Text
0 ENU a
0 JPN b
0 DAN c
1 ENU d
1 JPN e
1 DAN f
2 etc...
…for which they want results sorted non-alphabetically by Language, in the following order: ENU, JPN, DAN.
The accepted answer says to use the MySQL FIELD
command, like so:
ORDER BY FIELD(Language,'ENU','JPN','DAN'), ID
My question is this: FIELD returns a numeric value by order, and sorts on that. So in the above, "ENU" is 1, "JPN" is 2, and "DAN" is 3. If there is a value presented that is not explicitly listed in the FIELD function, it returns 0; which means the unspecified values will come first in the sorting. Is there any way to have unexpected values sort after the custom-sorted values? So if I’m sorting with that ORDER, and a record has a language of "RUS", that record would sort last instead of first? If we have both "RUS" and "ESP", it would do the custom sort first, followed by the unexpected values alphabetically?
(I’m aware of CASE/WHEN, but FIELD is so much cleaner and compact, I was wondering if the same can be done in a similar manner to FIELD.)
2
Answers
Based on @bill-karwin 's answer, this works perfectly:
The difference is this sorts the unexpected values alphabetically after the custom sorted values.
This is the one that puts unknown languages at the start:
Here are two solutions that put the unknown languages at the end:
Dbfiddle