I have a column named MR which is a varchar. When I run a query with an ORDER BY it doesn’t seem to be ordered correctly.
select MR, LName, FName
from users
order by MR
Results:
MR | LNAME | FNAME
----------+-------+-------
1234-234 | HEN | LO
2343MA2 | SY | JACK
MR20001 | LINA | MARY
MR200011 | TEST | CASE
MR20002 | KO | MIKE
Why does MR200011 show before MR20002?
Any Idea guys on how I can properly sort this? The format of MR is not fixed.
You are sorting by string, not by the value of the number. The character in position 7 is the difference that’s being compared:
And because ‘2’ > ‘1’, this is the order you end up with. The 8th character is never compared, because the character-based sort order doesn’t depend on it.
To ‘fix’ this issue, create a stored function which takes your varchar value, and returns a new ‘sort string’ which pads the numeric components to a fixed length.
e.g.
but more importantly, if you have two blocks of numbers, they don’t become corrupted:
The following function performs this transformation on sql-server – you’d have to adapt this function for mysql:
Then change your
order byclause to use the new function:If you have a large amount of data, it would be worth adding a calculated field to the end of your table definition (populated by this function) so that you don’t have to do a scan every time you run this query.