
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
Sum Varchar Column and Display Count in MySQL
For this, use GROUP BY along with COUNT(*). Let us first create a table −
mysql> create table DemoTable ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeGender varchar(40) ); Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(EmployeeGender) values('FEMALE'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(EmployeeGender) values('FEMALE'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(EmployeeGender) values('FEMALE'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(EmployeeGender) values('MALE'); Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+----------------+ | EmployeeId | EmployeeGender | +------------+----------------+ | 1 | MALE | | 2 | FEMALE | | 3 | FEMALE | | 4 | FEMALE | | 5 | MALE | | 6 | MALE | | 7 | MALE | +------------+----------------+ 7 rows in set (0.00 sec)
Following is the query to sum the varchar column. This will sum the MALE and FEMALE column values and count would be displayed −
mysql> select EmployeeGender,count(*) from DemoTable group by EmployeeGender;
This will produce the following output −
+----------------+----------+ | EmployeeGender | count(*) | +----------------+----------+ | MALE | 4 | | FEMALE | 3 | +----------------+----------+ 2 rows in set (0.00 sec)
Advertisements