Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL order by column name

I have some data from excel exported to a MySql server. I want to do a query with results sorted with column names as in excel.

I had this query statement:

SELECT CellValue, Col, Row FROM cell WHERE Col != "A" ORDER BY Col ASC;

But the result is order in a way, not what I expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

AA, AB, AC, B, BA, C, CA, CB, ...  

What I want is

B, C, AA, AB, ...

What should I change/add to the query statement to have my wanted results?

>Solution :

Use a two-tier sort, first by the length of col, followed by the value of col:

SELECT CellValue, Col, `Row`
FROM cell
WHERE Col != 'A'
ORDER BY LENGTH(Col), Col;

Note that ROW became a reserved MySQL keyword as of MySQL 8+. You should avoid using this as a name for your columns (or tables).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading