Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql Max behaviour with numeric vals in varchar field

Tags:

mysql

max

We have a database table that has keys and values where the value can be anything in a varchar field. The values are for attributes about an item and one attribute is price.

To make a select field for prices, I was using the Max() function to find the greatest value in the value column which seemed to work.

Then when we got prices over £100, they started to not get returned as the max value. I under stand that this is because it is a string value and not numeric.

The confusion comes when running a command like select max(value) from attributes where value > 100 because now the statement recognises that 101 is > 100 but 99 is not so returns 101 as the max value, however without the where value > 100 clause, 99 is treated as > 101. Why does the > 100 clause work as a numeric comparison but max does not?

Is there a reason that this happens?

like image 407
Luke Avatar asked Sep 05 '11 10:09

Luke


1 Answers

Do not mixed varchar with numeric,
idea solution is only stored numeric for used of max aggregate function,
alternatively

max( cast(value as unsigned) )

When you are doing a MAX, is a cast to string.
When you are doing comparison, is a cast to numeric.

Reason?
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_max
(it returns the maximum string value)

like image 70
ajreal Avatar answered Oct 19 '22 17:10

ajreal