When SUM is used in query on field of type VARCHAR in MySql database, does SUM automatically convert it into number ? I tried this by using
SELECT SUM(parametervalue) FROM table
and it reveals that MySql returns the sum although I expected to throw it an error as "parametervalue" field is of VARCHAR type
MySQL does silent conversion for a string in a numeric context. Because it expects a number for the sum()
, MySQL simply does the conversion using the leading "numbers" from a string. Note that this include decimal points, minus sign, and even e
representing scientific notation. So, '1e6'
is interpreted as a number.
In code, I personally would make the conversion explicit by adding 0
:
SELECT SUM(parametervalue + 0) FROM table
Ironically, the cast()
might return an error if the string is not in a numeric format, but this doesn't return an error in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With