COUNT() - MySQL Aggregate Function
The count() function is a MySQL aggregate function that returns the number of rows that match a specified condition in a table. In this tutorial, we'll cover the syntax, usage, and examples of the MySQL count() function.
Syntax
The basic syntax of the count() function is as follows:
SELECT COUNT(column_name) FROM table_name WHERE condition;
In the syntax above, column_name
is the name of the column that you want to count the number of rows for and table_name
is the name of the table that contains that column. You can also add the optional WHERE
clause to count only the rows that meet a specific condition.
Example
Suppose you have a table named employees
that looks like this:
id | name | age |
---|---|---|
1 | John | 25 |
2 | Jane | 35 |
3 | Peter | 42 |
4 | Mary | 29 |
5 | Jack | 31 |
To count the number of rows in the employees
table, you would use the following query:
SELECT COUNT(*) FROM employees;
This query would return the total number of rows in the employees
table:
+----------+
| COUNT(*) |
+----------+
| 5 |
+----------+
Explanation
In the example above, the count() function is used to count the total number of rows in the employees
table. Since we didn't specify any condition, count() function counts all the rows in the table and returns the count as a single value.
Use
The count() function is very useful when you want to know the number of rows that match a specific condition in a table. For instance, you can use it to find out:
- The number of employees in a company
- The number of items sold in a store
- The number of orders placed by a customer
- The number of students who passed an exam
- And many more
Important Points
- The count() function returns the count as a single value.
- You can use the count() function with the
*
to count all the rows in a table or with a specific column name to count the number of rows that match a specified condition. - The count() function is often used in combination with other SQL commands, such as SELECT, WHERE, and GROUP BY.
Summary
The count() function is used to count the number of rows that match a specified condition in a table. It is a useful MySQL aggregate function that can be used in a variety of situations to answer a variety of questions about your data. In this tutorial, you learned how to use the count() function, including the syntax, example, explanation, use, and important points of the function.