Sfwd favicon 152

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] Incorrect result!!! */

SELECT number FROM posts ORDER BY number+0 ASC, number ASC
/* ==> [1A,2A,10A,20A] Produces correct result! */

Related External Links:

Posted in Web Development and Tagged with sql natural_sort 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts