COUNT()
function returns the number of rows that matches a specified criteria.
I am
going to use following sample data.
CREATE
TABLE employee(
id int PRIMARY KEY,
name VARCHAR(25),
age int,
salary DECIMAL(10, 4),
mailId VARCHAR(25),
city
VARCHAR(10)
);
INSERT
INTO employee VALUES (1, "Hari", 28, 12345.67,
"hari@hari.com", "Bangalore");
INSERT
INTO employee VALUES (2, "Sandesh", 31, 98345.00,
"sandesh@sandesh.com", "Trivendram");
INSERT
INTO employee VALUES (3, "Phalgum", 33, 119345.67,
"phalgun@hari.com", "Hyderabad");
INSERT
INTO employee VALUES (4, "Manju", 36, 87666.87,
"manju@sandesh.com", "Bangalore");
INSERT
INTO employee VALUES (5, "Rakesh", 26, 38000,
"rakesh@hari.com", "Bangalore");
INSERT
INTO employee VALUES (6, "Sankalp", 38, 87645.67,
"sankalp@sankalp.com", "Chenai");
INSERT
INTO employee VALUES (7, "Vadiraj", 40, 12345.67,
"vadi@hari.com", "Bangalore");
INSERT
INTO employee VALUES (8, "Prasob", 37, 12345.67,
"prasob@sandesh.com", "Trivendram");
INSERT
INTO employee (id, name, salary) VALUES (9, "Kesav", 123457.89);
mysql> SELECT * FROM employee; +----+---------+------+-------------+---------------------+------------+ | id | name | age | salary | mailId | city | +----+---------+------+-------------+---------------------+------------+ | 1 | Hari | 28 | 12345.6700 | hari@hari.com | Bangalore | | 2 | Sandesh | 31 | 98345.0000 | sandesh@sandesh.com | Trivendram | | 3 | Phalgum | 33 | 119345.6700 | phalgun@hari.com | Hyderabad | | 4 | Manju | 36 | 87666.8700 | manju@sandesh.com | Bangalore | | 5 | Rakesh | 26 | 38000.0000 | rakesh@hari.com | Bangalore | | 6 | Sankalp | 38 | 87645.6700 | sankalp@sankalp.com | Chenai | | 7 | Vadiraj | 40 | 12345.6700 | vadi@hari.com | Bangalore | | 8 | Prasob | 37 | 12345.6700 | prasob@sandesh.com | Trivendram | | 9 | Kesav | NULL | 123457.8900 | NULL | NULL | +----+---------+------+-------------+---------------------+------------+ 9 rows in set (0.00 sec)
Count number of employees in
employee table.
mysql> SELECT COUNT(*) FROM employee; +----------+ | COUNT(*) | +----------+ | 9 | +----------+ 1 row in set (0.00 sec)
Count number of employees staying in
Bangalore
mysql> SELECT COUNT(*) FROM employee WHERE city="Bangalore"; +----------+ | COUNT(*) | +----------+ | 4 | +----------+ 1 row in set (0.00 sec)
Display city and count of employees
mysql> SELECT city, COUNT(*) FROM employee GROUP BY city; +------------+----------+ | city | COUNT(*) | +------------+----------+ | NULL | 1 | | Bangalore | 4 | | Chenai | 1 | | Hyderabad | 1 | | Trivendram | 2 | +------------+----------+ 5 rows in set (0.00 sec)
As you
see it display the NULL values also, you can escape NULL values using following
query.
mysql> SELECT city, COUNT(*) FROM employee WHERE CITY IS NOT NULL GROUP BY city; +------------+----------+ | city | COUNT(*) | +------------+----------+ | Bangalore | 4 | | Chenai | 1 | | Hyderabad | 1 | | Trivendram | 2 | +------------+----------+ 4 rows in set (0.00 sec)
No comments:
Post a Comment