Cog

How To Easily Do A Natural Sort With SQL

Posted by Weston Ganger on September 22, 2016

Sometime when using SQL to order some data it doesn’t sort correctly. Heres is one super simple trick to naturally order in these cases.


For example given the following post numbers: [2A,1A,10A,20A]


# Using normal ORDER BY
SELECT number FROM posts ORDER BY number ASC
#==> [1A,10A,2A,20A] Wrong!!!

SELECT number FROM posts ORDER BY number + 0 ASC
#==> [1A,2A,10A,20A] Correct Answer!


Related External Links:


Posted in Web Development and Tagged with sql natural_sort 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts