Tomas Karafa
Tomas Karafa

Reputation: 3

max() function not getting largest value

i have a table "orders" in mysql database , which contains column "order_number" . And because each order has several rows ( depending on size of the eshop order ) , the column "order_number" looks like this :

1
1
1
2
2
2
2
2
3
3
3

.... etc ... currently there is about 1000 orders , which means several thousands rows in table . What i am trying to do is just retrieve highest order number ... sounds easy enough :

$result=mysql_query("SELECT max(order_number) as max FROM orders");
$lastordernumber = mysql_fetch_array($result);
echo $lastordernumber["max"];

...and this returns "99" , while currently highest order number is close to 1000 . any ideas ?

thanks !

Upvotes: 0

Views: 97

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270773

This occurs when the "order_number" is a string. You should store it as a numeric value, if that is what you want it to be. However, you can treat it as numeric for the purposes of this query:

select max(order_number + 0) as max
from orders;

Alternatively, you could write the query as:

select order_number
from orders
order by len(order_number) desc, order_number desc
limit 1;

Upvotes: 1

Related Questions