Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SUM(`column`) returns a string instead of an integer?

Tags:

php

mysql

pdo

I'm using Laravel and have a query that selects using DB::raw() SUM() of a column:

DB::raw("SUM(points) as game_points")

I have installed mysqldn and AFAIK Laravel uses PDO.

But game_points is a string, no matter what type of the column is. (It's an integer column)

Also if I do:

DB::raw("COUNT(id) as foo_bar")

foo_bar is returned as an integer.

like image 438
Ivanka Todorova Avatar asked Mar 17 '16 09:03

Ivanka Todorova


People also ask

What is the return type of SUM ()?

SUM returns data type INTEGER for an expression with data type INT, SMALLINT, or TINYINT. SUM returns data type BIGINT for an expression with data type BIGINT. SUM returns data type DOUBLE for an expression with data type DOUBLE. For all other numeric data types, SUM returns data type NUMERIC.

How do I sum in laravel query?

We mostly required to get sum of amount, salary etc in laravel. We can also get sum of column using mysql SUM(). We have two way to get sum of column value. first we can use laravel sum() of query builder and another one we can use with directly with select statement using DB::raw().


1 Answers

It's neither Laravel or PDO issue.

According to the manual, SUM() returns a DECIMAL value for exact-value arguments (integer or DECIMAL). And the only way to represent DECIMAL type in PHP is string, for two reasons:

  • it can overflow the PHP's int type, being bigger than PHP_INT_MAX.
  • also, in case the returned value being a decimal number, it can lose precision due to inherently imprecise nature of floating point numbers

due to these precautions the returned value is a string and you are supposed to convert it manually according to the expecting value - either using standard PHP type casting or using some dedicated math functions such as bcmath.

like image 166
Your Common Sense Avatar answered Sep 20 '22 16:09

Your Common Sense