Sum values of a single row in MySQL?


You can use below syntax to sum values of a single row −

Case 1 − The following is the syntax if your column does not have NULL value −

SELECT yourColumnName1+yourColumnName2+yourColumnName3+.......+N as anyVariableName FROM yourTableName;

Case 2 − If your column has NULL value then use this syntax −

SELECT IFNULL(yourColumnName1,0)+ IFNULL(yourColumnName2,0)+ IFNULL(yourColumnName3,0)+.............+N
AS anyVariableName FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table SumValueOfSingleRow
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FirstValue int,
   -> SecondValue int,
   -> ThirdValue int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into SumValueOfSingleRow(FirstValue,SecondValue,ThirdValue) values(1,0,1);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SumValueOfSingleRow(FirstValue,SecondValue,ThirdValue) values(1,NULL,0);
Query OK, 1 row affected (0.19 sec)

mysql> insert into SumValueOfSingleRow(FirstValue,SecondValue,ThirdValue) values(NULL,NULL,NULL);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from SumValueOfSingleRow;

The following is the output −

+----+------------+-------------+------------+
| Id | FirstValue | SecondValue | ThirdValue |
+----+------------+-------------+------------+
|  1 |          1 |           0 |          1 |
|  2 |          1 |        NULL |          0 |
|  3 |       NULL |        NULL |       NULL |
+----+------------+-------------+------------+
3 rows in set (0.00 sec)

Look at the sample output. If you use CASE 1, then you won’t get appropriate result.

Let us check CASE 1, which we discussed above. The query is as follows −

mysql> select FirstValue+SecondValue+ThirdValue as SingleRowSum from SumValueOfSingleRow;

The following is the output −

+--------------+
| SingleRowSum |
+--------------+
|            2 |
|         NULL |
|         NULL |
+--------------+
3 rows in set (0.06 sec)

Look at the sample output, the above query does not handle the NULL case. Now you can use the CASE 2 to get the appropriate result.

The query is as follows −

mysql> select ifnull(FirstValue,0)+ ifnull(SecondValue,0)+ ifnull(ThirdValue,0) as SingleRowSum from SumValueOfSingleRow;

The following is the output displaying the sum of values of a single row −

+--------------+
| SingleRowSum |
+--------------+
|            2 |
|            1 |
|            0 |
+--------------+
3 rows in set (0.06 sec)

Updated on: 30-Jul-2019

904 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements