Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour of SUM and CONCAT in MySql

If I want to make a sum of a specific numeric column in MySQL, I do

SELECT SUM(MyColumn) FROM MyTable WHERE 1;

This returns for example number 100.

But I'd like to prepend some text to the sum value, so I do

SELECT CONCAT('Sum is: ',SUM(MyColumn)) FROM MyTable WHERE 1;

but instead of getting Sum is: 100 I get something like 546573743a20343030.

Is this a bug or a feature? What am I doing wrong?

UPDATE

SELECT CONCAT('Sum is: ',CAST(SUM(MyColumn) AS varchar(20))) FROM MyTable WHERE 1;

Casting to varchar doesn't work: getting SQL syntax error.

like image 439
NumberFour Avatar asked Feb 25 '14 18:02

NumberFour


People also ask

What does concat do in MySQL?

MySQL CONCAT() Function The CONCAT() function adds two or more expressions together.

How do I concatenate more than two columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

Which operator concatenates two strings in a query result in MySQL?

CONCAT function is a SQL string function that provides to concatenate two or more than two character expressions into a single string.

How do I concatenate two column values in SQL?

Query: SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function.


1 Answers

As FreshPrinceOfSO suggested in the comments below my question, MySQL server doesn't handle casts to varchar.

So even though the query

SELECT CONCAT('Sum is: ',CAST(SUM(MyColumn) AS varchar(20))) FROM MyTable WHERE 1;

results in syntax error, casting to char instead works just fine:

SELECT CONCAT('Sum is: ',CAST(SUM(MyColumn) AS char(20))) FROM MyTable WHERE 1;
like image 69
NumberFour Avatar answered Oct 26 '22 22:10

NumberFour