The MySQL count function is used when we want to get the number of non-NULL rows returned by a MySQL select query.
You can use the COUNT function to quickly determine the number of rows in a table which satisfy a certain condition.
For example, if you had an employees table, you could easily count how many persons were in that table, and hence get the number of employees.
The MySQL count tutorial below explains.
Suppose our "employees" table looks like:
id | first_name | last_name |
---|---|---|
1 | Paul | Pitterson |
2 | Francine | Beecham |
3 | Raul | DiNozzo |
4 | Anthony | DiNozzo |
To determine how many employees we have, we could use the following SQL:
SELECT COUNT(id) FROM employees;
This will return:
COUNT(id) |
---|
4 |
The SQL we wrote is similar to "SELECT id FROM employees" except that we insert the COUNT function to count the number of rows that was returned.
Since there are 4 rows in the id column, then the COUNT function returns 4. It is as simple as that.
Suppose our "employees" table looks like:
id | first_name | last_name |
---|---|---|
1 | Paul | Pitterson |
2 | Francine | Beecham |
3 | Raul | DiNozzo |
4 | Anthony | DiNozzo |
Suppose we want to get the number of persons with a particular last name, we use:
SELECT last_name, COUNT(first_name) FROM employees GROUP BY last_name;
This would give:
last_name | COUNT(first_name) |
---|---|
Beecham | 1 |
DiNozzo | 2 |
Pitterson | 1 |
This SQL is a bit advanced, but all it does is leverage the COUNT function to determine the number of different last names in our table. Feel free to try our examples on your own database.
We hope this MySQL tutorial was helpful.