MYSQL: COUNT() reference
10 September 2023 (Updated 10 September 2023)
In a nutshell
The COUNT()
function counts the number of items in a result set.
Variations
COUNT(*)
Returns the number of rows in a table or group (when used with the GROUP BY
clause). It includes rows with NULL
values.
Example without GROUP BY
to count total number of employees:
SELECT COUNT(*) FROM employees;
Example with GROUP BY
to count the number of employees by department_id
:
SELECT department_id, COUNT(*) as number_of_employees
FROM employees
GROUP BY department_id;
COUNT(column_name)
Returns the number of non-NULL
values in the specified column. Rows where the specified column is NULL
aren’t counted.
Example:
SELECT COUNT(employee_id) FROM employees;
COUNT(DISTINCT column_names)
Counts the number of distinct non-NULL
values in the specified column. Useful to determine the number of unique values in the specified column
Example:
SELECT COUNT(DISTINCT department_id) FROM employees;
Tagged:
MySQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment