Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql SUM of VARCHAR fields without using CAST

Tags:

mysql

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

like image 917
AdityaKapreShrewsburyBoston Avatar asked Dec 20 '22 13:12

AdityaKapreShrewsburyBoston


1 Answers

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.

like image 182
Gordon Linoff Avatar answered Apr 28 '23 09:04

Gordon Linoff