The COUNT() function is an aggregate function in MySQL used to return the number of rows that match a specified criterion. It is commonly used in reporting to calculate totals, such as the number of orders, active users, or products in a category.
COUNT(*) includes NULLs, while COUNT(column) ignores them.GROUP BY to count items per category.There are three main ways to use the function:
-- 1. Count ALL rows in the 'employees' table (fastest method)
SELECT COUNT(*) FROM employees;
-- 2. Count only employees who have a manager (ignores NULL manager_id)
SELECT COUNT(manager_id) FROM employees;
-- 3. Count unique job titles available in the company
SELECT COUNT(DISTINCT job_title) FROM employees;
Counting records per category is one of the most common use cases.
-- Count the number of employees in each department
SELECT
department_name,
COUNT(*) as employee_count
FROM employees
GROUP BY department_name;
-- Filter groups: Show only departments with more than 5 employees
SELECT
department_name,
COUNT(*) as employee_count
FROM employees
GROUP BY department_name
HAVING COUNT(*) > 5;
Scenario: You have an employees table with 10 rows. 2 employees have no manager (NULL).
SELECT COUNT(*) → Returns 10 (Total rows).SELECT COUNT(manager_id) → Returns 8 (Only non-null managers).SELECT COUNT(DISTINCT job_title) → Returns the number of unique roles (e.g., 4).COUNT(*) is generally optimized and faster than COUNT(column) if you just need the total row count.COUNT() returns 0 if no rows match, not NULL.AS total_orders) to make the result readable in your application code.users table.email_verified_at column exists).GROUP BY customer_id.