SQL – Custom Sort Order Techniques

order-by

Suppose I have a column with colour names (colour). Naturally, it will be a character field.

I would like to sort the table by colour, but not in alphabetical order, but by rainbow or transistor colour code order.

What is the simplest way to sort a column using an arbitrary sort order? Something like this:

id  name        colour
1   this        red
4   that        red
2   stuff       orange
5   nonsense    orange
3   whatever    yellow
6   etc         yellow

where the colours in in rainbow order.

The use of colours is just an example. There are many sets of textual data where the order is not alphabetical.

Best Answer

I would use another table with the key values (also suggested by @McNets) feel its less verbose and more scalable.

-----------------------------
|         Colours           |
-----------------------------
|  KeyValue  |    Name      |
-----------------------------
|     1      |  Red         |
|     2      |  Orange      |
|     3      |  Yellow      |
-----------------------------

-----------------------------
|        OtherTable         |
-----------------------------
| id |  Name    |  Colour   |
-----------------------------
| 1  | this     |   red     |
| 4  | that     |   red     |
| 2  | stuff    |   orange  |
| 5  | nonsense |   orange  |
| 3  | whatever |   yellow  |
| 6  | etc      |   yellow  |
-----------------------------

SELECT
    ot.Id,
    ot.Name,
    ot.Colour
FROM OtherTable ot
INNER JOIN Colours c on c.Name = ot.Colour
ORDER BY c.KeyValue