How to use count with CASE condition in a MySQL query?

MySQLMySQLi Database

Use CASE WHEN for this in MySQL and set CASE condition inside the COUNT() method to count. Let us first create a table −

mysql> create table DemoTable1374
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> Score int
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1374(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1374(Name,Score) values('David',78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Bob',45);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1374(Name,Score) values('Mike',75);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1374(Name,Score) values('Carol',45);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1374(Name,Score) values('Adam',89);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1374;

This will produce the following output −

+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
|  1 | Chris |    45 |
|  2 | David |    78 |
|  3 | Bob   |    45 |
|  4 | Mike  |    75 |
|  5 | Carol |    45 |
|  6 | Adam  |    89 |
+----+-------+-------+
6 rows in set (0.00 sec)

Following is the query for CASE WHEN to set condition and count −

mysql> select count( case when Score=45 then 1 else NULL end) as  SpecificCondition from DemoTable1374;

This will produce the following output −

+-------------------+
| SpecificCondition |
+-------------------+
|                 3 |
+-------------------+
1 row in set (0.00 sec)
raja
Published on 11-Nov-2019 13:56:43
Advertisements