Apply natural sorting on MySQL or Postgres

If you have a table with a varchar or text column, which may or may not contain text-based integer values, it’s sometimes hard to do natural sorting on MySQL or Postgres. By that what I mean is, if you have

col1
——
a1
a2
a10
a20

and if you apply “order by col1″, the sorting result would be something like

col1
——
a1
a10
a2
a20

The easiest way to go around this is to first order by the length of the value and then the actual value. So in MySQL, you will have

… order by LENGTH(col1) ASC, col1 ASC

and in Postgres

.. order by CHAR_LENGTH(col1) ASC, col1 ASC

WA~LA~ saved me time.

About Eric

ericbae.com - just a small place for me to jot down whatever I need to jot down. not much here. so don't get too disappointed. i won't.
This entry was posted in Anything & Everything. Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>