Syntax error How to perform SELECT using COUNT in MySQL?

How to perform SELECT using COUNT in MySQL?



To perform SELECT with COUNT, use aggregate function COUNT(). Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Subject) values('John','MySQL');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name,Subject) values('John','Java');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name,Subject) values('Carol','MongoDB');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Subject) values('Carol','Java');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name,Subject) values('Carol','MySQL');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Name,Subject) values('John','MySQL');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(Name,Subject) values('Carol','MongoDB');
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+-------+---------+
| Id | Name  | Subject |
+----+-------+---------+
| 1  | John  | MySQL   |
| 2  | John  | Java    |
| 3  | Carol | MongoDB |
| 4  | Carol | Java    |
| 5  | Carol | MySQL   |
| 6  | John  | MySQL   |
| 7  | Carol | MongoDB |
+----+-------+---------+
7 rows in set (0.00 sec)

Following is the query to select using count in MySQL −

mysql> select Name,Subject,count(Subject) from DemoTable group by Subject,Name;

Output

+-------+---------+----------------+
| Name  | Subject | count(Subject) |
+-------+---------+----------------+
| John  | MySQL   | 2              |
| John  | Java    | 1              |
| Carol | MongoDB | 2              |
| Carol | Java    | 1              |
| Carol | MySQL   | 1              |
+-------+---------+----------------+
5 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements