
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL Query to Get the Count of All Elements in a Field
For this, use the COUNT() method. Let us first create a table −
mysql> create table DemoTable -> ( -> ProductName varchar(100) -> ); Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Product-1'); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable values('Product-2'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Product-3'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Product-3'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values('Product-2'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Product-4'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Product-5'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Product-1'); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+-------------+ | ProductName | +-------------+ | Product-1 | | Product-2 | | Product-3 | | Product-3 | | Product-2 | | Product-4 | | Product-5 | | Product-1 | +-------------+ 8 rows in set (0.00 sec)
Following is the query to get the count of all the elements in the field −
mysql> select ProductName,count(ProductName) as TotalCount from DemoTable group by ProductName;
Output
This will produce the following output −
+-------------+------------+ | ProductName | TotalCount | +-------------+------------+ | Product-1 | 2 | | Product-2 | 2 | | Product-3 | 2 | | Product-4 | 1 | | Product-5 | 1 | +-------------+------------+ 5 rows in set (0.05 sec)
Advertisements