Search code examples
phpmysqlsortingalphabetical

MySQL : order a query according to a certain alphabetical order


I would like to order a MySQL query according to a certain alphabetical order. More precisely, the starting letter of the alphabet could change, depending on the webpage.

For instance, I would like to order by query based on these orders:

[B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A] or [H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A,B,C,D]

Let's assume my query, very simple, looks like this:

SELECT name
FROM table
ORDER BY name ASC

Would it be possible to do this only with MySQL?

Thanks a lot.


Solution

  • SELECT * FROM my_table;
    +-----+---------------+
    | id  | element       |
    +-----+---------------+
    |  88 | Actinium      |
    |  12 | Aluminium     |
    |  94 | Americium     |
    ...
    |  69 | Ytterbium     |
    |  38 | Yttrium       |
    |  29 | Zinc          |
    |  39 | Zirconium     |
    +-----+---------------+
    
    SELECT * FROM my_table ORDER BY element <'M',element;
    +-----+---------------+
    | id  | element       |
    +-----+---------------+
    |  11 | Magnesium     |
    |  24 | Manganese     |
    | 108 | Meitnerium    |
    ...
    |  81 | Lead          |
    |   2 | Lithium       |
    | 115 | Livermorium   |
    |  70 | Lutetium      |
    +-----+---------------+