How to select sum or 0 if no records exist in MySQL?

MySQLMySQLi Database

You can use aggregate function sum() inside COALESCE(). The below syntax returns the sum of all if the record exists otherwise 0 is returned. The syntax is as follows.

select COALESCE(sum(yourColumnName2), 0) AS anyVariableName from yourTableName
where yourColumnName1 like '%yourValue%';

To understand the above syntax, let us create a table. The query to create a table is as follows.

mysql> create table SumDemo
-> (
-> Words varchar(100),
-> Counter int
-> );
Query OK, 0 rows affected (0.93 sec)

Insert some records in the table using insert command. The query is as follows.

mysql> insert into SumDemo values('Are You There',10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SumDemo values('Are You Not There',15);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SumDemo values('Hello This is MySQL',12);
Query OK, 1 row affected (0.09 sec)

mysql> insert into SumDemo values('Hello This is not MySQL',14);
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement. The query is as follows.

mysql> select *from SumDemo;

The following is the output.

+-------------------------+---------+
| Words                   | Counter |
+-------------------------+---------+
| Are You There           | 10      |
| Are You Not There       | 15      |
| Hello This is MySQL     | 12      |
| Hello This is not MySQL | 14      |
+-------------------------+---------+
4 rows in set (0.00 sec)

Here is the query that gives the total sum whenever record exist.

mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%hello%';

The following is the output.

+----------+
| SumOfAll |
+----------+
| 26       |
+----------+
1 row in set (0.00 sec)

If record does not exist then you will get 0. The query is as follows.

mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%End of MySQL%';

The following is the output.

+----------+
| SumOfAll |
+----------+
| 0       |
+----------+
1 row in set (0.00 sec)
raja
Published on 11-Jan-2019 12:16:10
Advertisements