Can I use SUM() with IF() in MySQL?


Yes, you can use SUM() with IF() in MySQL. Let us first create a demo table:

mysql> create table DemoTable
(
   Value int,
   Value2 int
);
Query OK, 0 rows affected (0.51 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values(100,400);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(100,400);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(400,100);
Query OK, 1 row affected (0.14 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output

+-------+--------+
| Value | Value2 |
+-------+--------+
|   100 |    400 |
|   100 |    400 |
|   400 |    100 |
+-------+--------+
3 rows in set (0.00 sec)

Following is the query to use SUM() along with IF() that calculates how many 100s and 400s are in the above table:

mysql> SELECT SUM(IF(Value=100, 1, 0) + IF(Value2=100, 1, 0)) as Hundred,
SUM(IF(Value=400, 1, 0) + IF(Value2=400, 1, 0)) as FourHundred
FROM DemoTable;

This will produce the following output:

+---------+--------------+
| Hundred | FourHundred  |
+---------+--------------+
|       3 |            3 |
+---------+--------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements