To count the number of occurrences from a table, you can use aggregate function COUNT() with GROUP BY. The syntax is as follows −
SELECT yourColumnName,COUNT(*) as anyVariableName from yourTableName GROUP BY yourColumnName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table CountOccurrences -> ( -> CarId int not null auto_increment, -> CarName varchar(30), -> PRIMARY KEY(CarId) -> ); Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into CountOccurrences(CarName) values('Aston Martin'); Query OK, 1 row affected (0.10 sec) mysql> insert into CountOccurrences(CarName) values('BMW'); Query OK, 1 row affected (0.20 sec) mysql> insert into CountOccurrences(CarName) values('Aston Martin'); Query OK, 1 row affected (0.15 sec) mysql> insert into CountOccurrences(CarName) values('Honda'); Query OK, 1 row affected (0.20 sec) mysql> insert into CountOccurrences(CarName) values('BMW'); Query OK, 1 row affected (0.11 sec) mysql> insert into CountOccurrences(CarName) values('Audi'); Query OK, 1 row affected (0.18 sec) mysql> insert into CountOccurrences(CarName) values('Aston Martin'); Query OK, 1 row affected (0.11 sec) mysql> insert into CountOccurrences(CarName) values('Bugatti'); Query OK, 1 row affected (0.22 sec) mysql> insert into CountOccurrences(CarName) values('BMW'); Query OK, 1 row affected (0.27 sec) mysql> insert into CountOccurrences(CarName) values('Honda'); Query OK, 1 row affected (0.13 sec) mysql> insert into CountOccurrences(CarName) values('Audi'); Query OK, 1 row affected (0.13 sec) mysql> insert into CountOccurrences(CarName) values('BMW'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from CountOccurrences;
The following is the output −
+-------+--------------+ | CarId | CarName | +-------+--------------+ | 1 | Aston Martin | | 2 | BMW | | 3 | Aston Martin | | 4 | Honda | | 5 | BMW | | 6 | Audi | | 7 | Aston Martin | | 8 | Bugatti | | 9 | BMW | | 10 | Honda | | 11 | Audi | | 12 | BMW | +-------+--------------+ 12 rows in set (0.00 sec)
The following is the query to count the number of occurrences of each value in a column using count() with GROUP BY −
mysql> select CarName,count(*) as TotalCount from CountOccurrences -> group by CarName;
The following is the output −
+--------------+------------+ | CarName | TotalCount | +--------------+------------+ | Aston Martin | 3 | | BMW | 4 | | Honda | 2 | | Audi | 2 | | Bugatti | 1 | +--------------+------------+ 5 rows in set (0.00 sec)