so i have been learning mysql syntax about a 5 days now and there is this LENGTH function in mysql that count string length in the column like this:
SELECT id, LOWER(NAME) AS 'Name Lower', LENGTH(NAME) AS 'Name Length' FROM products;
id | Name Lower | Name Length |
---|---|---|
P0001 | mie ayam original | 17 |
P0002 | mie ayam baso tahu | 18 |
P0003 | mie ayam ceker | 14 |
P0004 | mie ayam special | 16 |
P0005 | mie ayam yamin | 14 |
P0006 | bakso rusuk | 11 |
P0007 | es jeruk | 8 |
P0008 | es campur | 9 |
P0009 | es teh manis | 12 |
P0010 | kerupuk | 7 |
P0011 | keripik udang | 13 |
P0012 | es krim | 7 |
P0013 | mie ayam jamur | 14 |
P0014 | bakso telor | 11 |
P0015 | bakso janda | 11 |
generated 2024-01-06 15:03:33 by HeidiSQL 12.6.0.6765
which lower string on column NAME and alias it to display as Name Lower column, next counting string length in NAME column and display it as alias ‘Name Length’ which is informative for me and i wonder how about i want to sort this alias column ?
then i tried this command;
SELECT id, LOWER(NAME) AS 'Name Lower', LENGTH(NAME) AS 'Name Length' FROM products
ORDER BY 'Name Length';
but it won’t sort the Name Length like what i want it to be.
so the solution is using back ticks, just like mention here in mysql docs.
this is the command to sort alias column in mysql using backticks:
SELECT id, LOWER(NAME) AS 'Name Lower', LENGTH(NAME) AS 'Name Length' FROM products
ORDER BY `Name Length` desc;
id | Name Lower | Name Length |
---|---|---|
P0002 | mie ayam baso tahu | 18 |
P0001 | mie ayam original | 17 |
P0004 | mie ayam special | 16 |
P0003 | mie ayam ceker | 14 |
P0005 | mie ayam yamin | 14 |
P0013 | mie ayam jamur | 14 |
P0011 | keripik udang | 13 |
P0009 | es teh manis | 12 |
P0006 | bakso rusuk | 11 |
P0014 | bakso telor | 11 |
P0015 | bakso janda | 11 |
P0008 | es campur | 9 |
P0007 | es jeruk | 8 |
P0010 | kerupuk | 7 |
P0012 | es krim | 7 |
generated 2024-01-06 15:13:20 by HeidiSQL 12.6.0.6765