We all know with MySQL you can use ORDER BY with a list of
columns to return an ordered set, e.g. ORDER BY name, type,
state;
I often use the syntax ORDER BY 1,2; which I’m surprised that
some people do not know about.
However I needed to do some selective ordering of a type field, I didn’t want to for example have a lookup table just to join for ordering. While contemplating a means of achieving this, I asked a work colleague, who I figured may have just experienced this problem before. Lone behold I became the student as I discovered there is a third syntax with ORDER BY, using expressions.
mysql> create table test(name varchar(10) not null, type varchar(10) not null); Query OK, 0 rows affected (0.06 sec) mysql> insert into test(name,type) values ('Apples','Fruit'), ('Bananas','Fruit'), ('Carrots','Veg'), ('Onions','Veg'), ('Beer','Liquid'), ('Water','Liquid'), ('Crackers','Food'); Query OK, 7 rows affected (0.00 sec) …[Read more]