Wednesday, December 18, 2024

SQL COUNT() Function

 The COUNT() function in SQL is used to return the number of rows in a result set. It is commonly used to count rows in a table, either including all rows or only those that match a specific condition.

Syntax

COUNT(expression)

Key Points:

  • COUNT(*): Counts all rows in a table, including those with NULL values.
  • COUNT(column_name): Counts only the non-NULL values in the specified column.
  • COUNT(DISTINCT column_name): Counts the unique non-NULL values in the specified column.

Examples

1. Count All Rows

SELECT COUNT(*) AS TotalRows FROM Employees;

Output: Total number of rows in the Employees table.


2. Count Non-NULL Values in a Column

SELECT COUNT(Salary) AS TotalSalaries FROM Employees;

Output: Counts the number of non-NULL values in the Salary column.


3. Count Unique Values

SELECT COUNT(DISTINCT Department) AS UniqueDepartments FROM Employees;

Output: Counts the distinct number of departments.


4. Count Rows with a Condition

SELECT COUNT(*) AS HighEarningEmployees FROM Employees WHERE Salary > 50000;

Output: Counts the number of employees earning more than 50,000.


Use with GROUP BY

The COUNT() function is often used with the GROUP BY clause to count rows for each group.

SELECT Department, COUNT(*) AS EmployeesPerDepartment FROM Employees GROUP BY Department;

Output: The count of employees in each department.

No comments:

Post a Comment