I have a table of orders. For each order, we allow the user to enter their (non-unique) order number. This can we whatever they want.
I have these orders displayed in an HTML table, with the ability to sort the orders by various fields, such as order number.
One of our clients noticed an issue with the sorting. Since the order numbers are stored as VARCHAR
, they are sorted lexicographically. Problem is, not all order numbers are numerc, some are words, and others are alphanumeric.
So, for example, I can have order numbers like so:
42
Order8
MyOrder
9
Order63
When sorted using ORDER BY orderNumber
, I get:
42
9
MyOrder
Order63
Order8
DEMO: http://sqlfiddle.com/#!2/7973e/1
This is not what I want. I want them to be sorted like so:
9
42
MyOrder
Order8
Order63
I want them to be lexicographical for the strings, but numeric for the numbers. I thought of something that might work:
ORDER BY IFNULL(NULLIF(CAST(orderNumber AS SIGNED), 0), orderNumber)
DEMO: http://sqlfiddle.com/#!2/7973e/2
But alas, I still get the same results (as the numbers are then re-cast back to strings). How can I sort these values in the way that I want? If only there was some way to "convert" the strings into a sort of numerical value.