The COUNT() function in SQL Server is an aggregate function used to count the number of rows that match a specified condition or all rows in a table. It is commonly used in SELECT queries to return the number of rows for a given condition.
Syntax:
SELECT COUNT(expression)
FROM table_name
WHERE condition;
- expression: The column or expression whose non-null values are counted.
- table_name: The table from which you want to count the rows.
- condition (optional): A condition to filter the rows.
Usage:
-
Count all rows in a table:
SELECT COUNT(*) FROM employees;This query returns the total number of rows in the
employeestable. -
Count rows with a specific condition:
SELECT COUNT(*) FROM employees WHERE department = 'Sales';This query counts the number of rows in the
employeestable where thedepartmentcolumn is 'Sales'. -
Count non-NULL values in a specific column:
SELECT COUNT(salary) FROM employees;This counts the number of non-NULL values in the
salarycolumn.
Notes:
COUNT(*)counts all rows, including rows with NULL values.COUNT(column_name)counts only the rows where the specified column is not NULL.- The
WHEREclause can be used to filter rows based on specific conditions.
No comments:
Post a Comment