MySQL Sum with If Condition Tutorial

Table of Contents

Share this Article
Reading Time: 3 minutes
2,121 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

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5