Press enter to see results or esc to cancel.

Sort VARCHAR as INT in MySQL

Sometimes we can user VARCHAR for integer values. But when we need sort them, we have got big problem. Because VARCHAR’s are string and it is sorting like a string.

Example:

1a 2a 3a 10b 20b 30b 15c 25c 35c (VARCHAR)

1a 10b 15c 2a 20b 25c 3a 30b 35c (Sorted)

We need

1a 2a 3a 10b 15c 20b 25c 30b 35c (Sorted integer)

We can do it with mysql CAST

SELECT vNumber FROM table ORDER BY CAST(`vNumber` AS SIGNED)
Reverse order
SELECT vNumber FROM table ORDER BY CAST(`vNumber` AS SIGNED) DESC
Other possible conversion types you may need are:
  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]
You can find more about CAST -> MySQL docs here.
Comments

Comments are disabled for this post