MySQL Sum Query with IF Condition using Stored Procedure


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 stored procedure that takes one string as a parameter −

mysql> delimiter //

mysql> create procedure sp_GetSumWithPaymentMode11(PaymentMode varchar(200))
−> begin
−> select PaymentMode,sum(if(ModeOfPayment=PaymentMode,Amount,0)) as TotalAmount from SumWithIfCondition;
−> end //
Query OK, 0 rows affected (0.32 sec)

mysql> delimiter ;

Now you can call the stored procedure using call command.

Case 1 − For Online

The query is as follows −

mysql> call sp_GetSumWithPaymentMode11('Online');

The following is the output −

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

Query OK, 0 rows affected (0.01 sec)

Case 2 − For Offline

The query is as follows −

mysql> call sp_GetSumWithPaymentMode11('Offline');

The following is the output −

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

Query OK, 0 rows affected (0.01 sec)

Updated on: 29-Jun-2020

556 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements