MySQL Sum with If Condition Tutorial

Table of Contents

Share this Article
Reading Time: 3 minutes
243 Views

Inside this article we will see the concept of MySQL Sum with if condition tutorial. This article contains a classified information about If Else condition in MySQL.

MySQL Sum with cases using if else conditional block is very useful when we need to calculate data of different cases in a single query. If else case block executes mysql queries into a conditional statement.

Learn More –

Let’s get started.


Consider Database Table Data

Let’s say we have a table in a database. Table contains data like this –

Inside above image we have a payment_mode column which stores data like Cash, Paypal, Bank Transfer.

We want to find the total sum according to payment_method.

SELECT 
	SUM(CASE 
		WHEN `payment_mode` = "Cash" 
		THEN amount 
		ELSE 0 END
		) AS total_cash, 
	SUM(CASE 
		WHEN `payment_mode` = "Bank Transfer" 
		THEN amount 
		ELSE 0 END
		) AS total_bank_transfer, 
	SUM(CASE 
		WHEN `payment_mode` = "Paypal" 
		THEN amount 
		ELSE 0 END) AS total_paypal 
FROM `finance_reports`

We hope this article helped you to learn about MySQL Sum with If Condition Tutorial in a very detailed way.

Buy Me a Coffee

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Learn Web Development Courses @ $4 only.
Web Development Courses @ $4