Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to query get max id from varchar type and the values in numeric?

Tags:

php

mysql

max

i have table and column id, and the values are 1, 2 ,3,...,10,11,12,13. how to query get max id from varchar type ? i had try

select MAX(id) from table

but the result is 9, Please help ??

like image 377
N4ta nata Avatar asked Feb 22 '12 08:02

N4ta nata


People also ask

How do I get maximum ID records in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

What is the maximum value of Max VARCHAR length?

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.

Can we use MAX function on VARCHAR?

MAX is an aggregate function that evaluates the maximum of an expression over a set of rows (see Aggregates (set functions)). MAX is allowed only on expressions that evaluate to built-in data types (including CHAR, VARCHAR, DATE, TIME, CHAR FOR BIT DATA, etc.).

How do I get the max value in a column in SQL?

The MAX() function returns the largest value of the selected column.


2 Answers

Looks like the values are strings and it selecting the maximum string. You have to cast them to numbers first if you want them to sort 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 nearly the same thing except CONVERT has some additional options if you need them.

like image 92
Ben Lee Avatar answered Oct 18 '22 19:10

Ben Lee


You can cast the varchar to an integer - something like

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

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

like image 3
Adam Hopkinson Avatar answered Oct 18 '22 17:10

Adam Hopkinson