MySQL COUNT() function
The COUNT()
function in MySQL is an aggregate function used to count the number of rows that match a specified condition or the number of non-NULL values in a column. It is widely used in SQL queries to summarize data and perform analysis.
Syntax
1. Count All Rows
COUNT(*)
- Counts the total number of rows in a table, including rows with NULL values.
2. Count Non-NULL Values in a Column
COUNT(column_name)
- Counts the number of non-NULL values in a specific column.
3. Count Unique Non-NULL Values
COUNT(DISTINCT column_name)
- Counts the number of unique non-NULL values in a specific column.
Examples
Count All Rows
To count the total number of rows in a table:
SELECT COUNT(*) AS total_rows FROM employees;
This query returns the total number of rows in the
employees
table.Count Non-NULL Values in a Column
To count the number of non-NULL values in a specific column:
SELECT COUNT(salary) AS total_salaries FROM employees;
This query counts the number of non-NULL values in the
salary
column of theemployees
table.Count Unique Values in a Column
To count the number of unique non-NULL values in a column:
SELECT COUNT(DISTINCT department) AS unique_departments FROM employees;
This query counts the number of unique departments in the
employees
table.Count Rows with a Condition
To count the number of rows that meet a specific condition:
SELECT COUNT(*) AS active_employees FROM employees WHERE status = 'Active';
This query counts the number of rows in the
employees
table where thestatus
column is 'Active'.Count Rows by Group
To count the number of rows for each group when using the
GROUP BY
clause:SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department;
This query retrieves the number of employees in each department.
Count with Multiple Conditions
To count rows that satisfy multiple conditions:
SELECT COUNT(*) AS senior_employees FROM employees WHERE position = 'Senior' AND salary > 50000;
This query counts the number of senior employees with a salary greater than 50,000.
Best Practices
- Use with
GROUP BY
:COUNT()
is often used with theGROUP BY
clause to provide counts for each group of data. - Include Non-Aggregated Columns: When using
GROUP BY
, ensure that all non-aggregated columns in theSELECT
clause are included in theGROUP BY
clause. - Filter Before Counting: Use the
WHERE
clause to filter data before applyingCOUNT()
to ensure accurate results based on specific criteria. - Avoid Unnecessary Counts: Be mindful of using
COUNT(*)
with large tables as it can be resource-intensive. Consider filtering or optimizing queries for better performance.