Sorting table by name (first letters then characters and numbers)
January 6th, 2012
So we have a problem: we have table with some name field(varchar 100) for example that have such rows:
id name
1 Belex
2 2LOL
3 Alex
so we need to sort this table in ascending order but in way those names starts with number should be after names which starts with letters
so if you make this query:
SELECT * FROM table1 ORDER BY name ASC
You’ll get this
2LOL
Alex
Belex
but we need:
Alex
Belex
2LOL
So here is solution:
SELECT * FROM table1 ORDER BY ORD(name) < 65 ASC, name ASC
In code above we used function ORD that takes first character’s integer code and then compare it to be less than letter code, almost all characters and numbers will have less value, after this we’r making ascending sorting, that is it.



