How to count the number of occurrences of a specific value in a column with a single MySQL query?


For this, you can use GROUP BY clause along with IN(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.87 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Chris |
|  3 | David |
|  4 | Chris |
|  5 | Chris |
|  6 | John  |
|  7 | Carol |
|  8 | Sam   |
+----+-------+
8 rows in set (0.00 sec)

Now, count the number of occurrences of a specific value in a column with a single query −

mysql> select Name,count(*) AS Occurrences from DemoTable
   -> where Name in('John','Chris') group by Name;

This will produce the following output −

+-------+-------------+
| Name  | Occurrences |
+-------+-------------+
| John  |           2 |
| Chris |           3 |
+-------+-------------+
2 rows in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jul-2019

703 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements