- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL COUNT
The COUNT() function is one of the most fundamental aggregate functions in SQL. Whether you are building a dashboard to show the total number of users or generating a report on monthly sales, you will find yourself using COUNT() constantly. At its core, it returns the number of rows that match a specific criterion.
COUNT() as a way to perform an inventory of your data. It’s the starting point for almost any data analysis task.
Syntax of SQL COUNT
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
- COUNT(): The function that performs the calculation.
- column_name: Specifies which column to evaluate. If you use
*, SQL counts every row regardless of its content. - table_name: The source table you are querying.
- condition: An optional filter to narrow down which rows should be included in the count.
AS total_count) when using the COUNT function. This makes your result set much easier to read and allows you to reference the count easily in your application code.
Key Points
- COUNT(*): This is the "catch-all" count. It includes every single row that matches your
WHEREclause, even if some columns containNULLvalues. - COUNT(column_name): This is more specific. It only counts rows where the specified column has a value (non-NULL).
- The Result: The output is always a single integer value (0 or higher).
COUNT(column_name) will skip rows where that column is NULL. If you need a total head-count of every record in the table, COUNT(*) is usually the safer choice.
Example of SQL COUNT
Let's look at how this works in practice. Suppose we have an Employees table that tracks our staff and their current salaries.
Table: Employees
If you need to know how many employees are currently on the payroll, you would run the following query:
SELECT COUNT(*) AS total_employees
FROM employees;
Output:
Explanation:
- By using COUNT(*), the database looks at the
employeestable and increments the counter for every row it finds. Since there are 5 entries, the result is 5.
SQL COUNT with a Specific Column
Sometimes you only want to count rows that contain valid data in a specific field. For instance, if you were counting how many employees have an assigned salary (excluding those whose salary might be unknown/NULL):
SELECT COUNT(salary) AS total_salaries
FROM employees;
Output:
Explanation:
- The COUNT(salary) syntax instructs SQL to count all non-NULL entries in the
salarycolumn. In our example table, every employee has a salary listed, so the count remains 5. However, if David's salary wasNULL, the count would return 4.
COUNT(column) and COUNT(*) are identical. Remember: COUNT(*) counts rows; COUNT(column) counts data.
SQL COUNT with Conditions
You can combine COUNT() with a WHERE clause to get more granular data. This is useful for answering specific questions, such as "How many employees earn a high salary?"
SELECT COUNT(*) AS high_salary_count
FROM employees
WHERE salary > 60000;
Output:
Explanation:
- In this case, the database filters the table first, keeping only Sarah (65,000) and David (70,000). Then, it applies the
COUNT(*)function to those filtered results, giving us a total of2.
SQL COUNT with Grouping
To see counts categorized by a specific group, we use COUNT() alongside the GROUP BY clause. Imagine our table had a department column. This allows you to see the distribution of staff across the company.
SELECT department, COUNT(*) AS department_count
FROM employees
GROUP BY department;
Output:
Explanation:
- The GROUP BY clause tells SQL to put employees into "buckets" based on their department. The COUNT() function then runs on each bucket separately.
department) and an aggregate function (like COUNT), you must include that column in a GROUP BY clause. Otherwise, most SQL engines will throw an error.
SQL COUNT with DISTINCT
What if you want to know how many unique values exist in a column? For example, if two employees earn the exact same salary, you might only want to count that salary once to see how many different pay levels exist.
SELECT COUNT(DISTINCT salary) AS unique_salaries
FROM employees;
Output:
Explanation:
- The DISTINCT keyword forces SQL to look at the set of salaries, remove all duplicates, and then count what remains. In our data, every salary was unique, so the count is still 5. If two people earned 50,000, the result would be 4.
Summary
The COUNT() function is a versatile tool for summarizing your data. By understanding the difference between COUNT(*) and COUNT(column), and knowing how to leverage WHERE, GROUP BY, and DISTINCT, you can extract meaningful insights from any database table. Always remember to use aliases to keep your results clean and developer-friendly!