ORDER BY numeric values in MySQL and PHP

Before entirely understanding MySQL syntax, I would get extremely frustrated when trying to execute a simple ORDER BY query for numbers, only to have “10” be listed before “1, 2, 3…etc”. If you have ever encountered an issue like this, than learning about the ABS operator is what you are looking for.

MySQL’s ORDER BY field is perfect when alphabetizing a list, but not when you are dealing with numbers. All you need to adjust is adding the ABS operator:

SELECT * FROM table ORDER BY ABS(number_field) ASC

The above query will properly order your number column.

This article has 1 comments

Leave a Comment

Your email address will not be published. Required fields are marked *