MySQL : ORDER BY numbers

Sat, May 9, 2009

MySQL

In this article I will show you how to order MySQL records by numeric values (numbers, integers & floats) from the smallest to the largest number or the other way around using a MySQL ORDER BY query.

A MySQL ORDER BY query with a given field name will order/sort the MySQL records alphabetically for the specified field name. If the field specified contains numbers, they will still be sorted alphabetically. Say we have 5 (five) records in the database table with the following values in the “price” field/column.

  • 19.99
  • 125
  • 5.99
  • 199
  • 300

Lets execute a normal ORDER BY MySQL on the table and attempt to order/sort the records by the “price” field in an ascending manner. See the query below.

SELECT * FROM `table` ORDER BY `price` ASC;

You might expect the query above to order records by price from the record with the smallest/lowest price in an ascending manner to the record with the biggest/highest price but this won’t necessarily happen. The records will be sorted with the “price” field in the following order.

  • 125
  • 199
  • 19.99
  • 300
  • 5.99

As you can see the numbers are being ordered alphabetically and not as expected from the smallest/lowest number to the biggest/highest number. You can get the correct order as expected though by using the MySQL ABS modifier. It tells MySQL to process the field as an absolute numeric value. See the example below with the MySQL ABS modifier.

SELECT * FROM `table` ORDER BY ABS(`price`) ASC;

The result of using MySQL ABS are the records ordered with the “price” field from the lowest price to the highest price as expected. This can be used with any MySQL field/column which holds numeric values. You can use this on INT, BIGINT, FLOAT and other MySQL field types.

  • 5.99
  • 19.99
  • 125
  • 199
  • 300
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • E-mail this story to a friend!
  • LinkedIn
  • Live
  • Ping.fm
  • StumbleUpon
  • Print this article!
  • Reddit
  • TwitThis
, , , , , , , , , , , , , ,
scriptlancebannerpng

This post was written by:

Antonie Potgieter - who has written 52 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

1 Comments For This Post

  1. IFO Says:

    Thanks for the tutorial!

Leave a Reply