MySQL Tips & Tricks

Thursday, February 12, 2009

ordering a text field numerically (A MySQL trap)

If whatever reason you have numbers stored in a text field (char, varchar etc)then watch out if you try and do an order by as it will do the sort alphanumerically this means it will sort 1,10,2,3,4,5,6,7,8,9 when you would expect 1,2,3,4,5,6,7,8,9,10

There is a work-around namely

SELECT names FROM your_table ORDER BY names + 0 ASC

where the +0 forces a numeric sort

This trap occurs in quite a few programming languages and can be hard to spot

Labels: , ,

0 Comments:

Post a Comment



<< Home