Easily Do A Natural Sort With SQL

Posted By Weston Ganger

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:

Article Topic:Software Development - Web Development

Date:September 22, 2016