![]() |
VOOZH | about |
The COUNT() function in SQL Server is a fundamental aggregate function used to determine the number of rows that match a specific condition. Counting rows provides valuable insights into data sets such as the total number of records, distinct values, or records meeting certain criteria.
In this article, We will learn the COUNT() Function in SQL Server by understanding various examples in detail.
COUNT() function in SQL Server is an aggregate function used to return the number of rows that match a specified condition. Syntax of the COUNT() function:
COUNT(expression)expression: The column or expression for which the count is calculated. It can be a column name, a constant, or an asterisk (*).
Consider the following example table named Employees:
| EmployeeID | Name | Department | Status |
|---|---|---|---|
| 1 | Alice | HR | Active |
| 2 | Bob | IT | Inactive |
| 3 | Charlie | HR | Active |
| 4 | David | IT | Active |
| 5 | Eve | Finance | Active |
Let's explore various ways to use the COUNT() function with this table.
Employees TableSELECT COUNT(*) AS TotalRows
FROM Employees;
Output:
| TotalRows |
|---|
| 5 |
Explanation: This query returns the total number of rows in the Employees table, which is 5.
Department ColumnSELECT COUNT(DISTINCT Department) AS UniqueDepartments
FROM Employees;
Output:
| UniqueDepartments |
|---|
| 3 |
Explanation: This query counts the number of unique departments in the Employees table, which are HR, IT, and Finance.
Status is 'Active'SELECT COUNT(*) AS ActiveEmployees
FROM Employees
WHERE Status = 'Active';
Output:
| ActiveEmployees |
|---|
| 4 |
Explanation: This query returns the number of employees with the status 'Active', which is 4.
SELECT Department, COUNT(*) AS NumberOfEmployees
FROM Employees
GROUP BY Department;
Output:
| Department | NumberOfEmployees |
|---|---|
| HR | 2 |
| IT | 2 |
| Finance | 1 |
Explanation: This query counts the number of employees in each department, providing a breakdown by department.
COUNT() with SUM() and AVG()Assuming the Employees table has a Salary column:
SELECT Department, COUNT(*) AS TotalEmployees, SUM(Salary) AS TotalSalary, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;
Output:
| Department | TotalEmployees | TotalSalary | AverageSalary |
|---|---|---|---|
| HR | 2 | 120000 | 60000 |
| IT | 2 | 150000 | 75000 |
| Finance | 1 | 80000 | 80000 |
Explanation: This query counts the number of employees, calculates the total salary, and finds the average salary for each department.
The COUNT() function is a powerful tool for summarizing data by counting rows based on given conditions or criteria. Whether you're calculating the total number of records, counting unique values, or aggregating data across groups, COUNT() provides crucial metrics that aid in data analysis.