How to request get max id from varchar type and value in numeric?

I have a table and column id, and the values ​​are 1, 2, 3, ..., 10,11,12,13. How to request get max id from varchar type? I tried

select MAX(id) from table

but the result is 9, please help?

+5
source share
3 answers

It appears that the values ​​are strings and select the maximum row. You must first transfer them to numbers if you want them to be sorted numerically. You can use CONVERT to do this:

SELECT MAX(CONVERT(id, SIGNED)) FROM table

You can also use CAST :

SELECT MAX(CAST(id AS SIGNED)) FROM table

They do almost the same thing, except that it CONVERThas some additional options if you need them.

+7

varchar - -

SELECT MAX(CONVERT(id, SIGNED)) FROM table

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_convert

+3

SELECT MAX(id+0) FROM the table will do the trick

+1
source

All Articles