MySQL Sum Query with IF Condition?


The Sum() is an aggregate function in MySQL. You can use sum query with if condition. To understand the sum query with if condition, let us create a table.

The query to create a table −

mysql> create table SumWithIfCondition
   −> (
   −> ModeOfPayment varchar(100)
   −> ,
   −> Amount int
   −> );
Query OK, 0 rows affected (1.60 sec)

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

mysql> insert into SumWithIfCondition values('Offline',10);
Query OK, 1 row affected (0.21 sec)

mysql> insert into SumWithIfCondition values('Online',100);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SumWithIfCondition values('Offline',20);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SumWithIfCondition values('Online',200);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SumWithIfCondition values('Offline',30);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SumWithIfCondition values('Online',300);
Query OK, 1 row affected (0.17 sec)

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

mysql> select *from SumWithIfCondition;

The following is the output −

+---------------+--------+
| ModeOfPayment | Amount |
+---------------+--------+
| Offline       |     10 |
| Online        |    100 |
| Offline       |     20 |
| Online        |    200 |
| Offline       |     30 |
| Online        |    300 |
+---------------+--------+
6 rows in set (0.00 sec)

Here is the sum query with if condition.

Case 1 - if for Online Mode of Payment

The query is as follows −

mysql> select sum(if(ModeOfPayment = 'Online',Amount,0)) as TotalAmount from SumWithIfCondition;

The following is the output −

+-------------+
| TotalAmount |
+-------------+
|         600 |
+-------------+
1 row in set (0.00 sec)

Case 2 - if for Offline Mode of Payment

The query is as follows −

mysql> select sum(if(ModeOfPayment = 'Offline',Amount,0)) as TotalAmount from SumWithIfCondition;

The following is the output −

+-------------+
| TotalAmount |
+-------------+
|          60 |
+-------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements