MySQL Sum with If Condition Tutorial

Reading Time: 3 minutes
2,985 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.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more