Thursday, December 26, 2024

SQL Server COUNT() Function

 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:

  1. Count all rows in a table:

    SELECT COUNT(*)
    FROM employees;
    

    This query returns the total number of rows in the employees table.

  2. Count rows with a specific condition:

    SELECT COUNT(*)
    FROM employees
    WHERE department = 'Sales';
    

    This query counts the number of rows in the employees table where the department column is 'Sales'.

  3. Count non-NULL values in a specific column:

    SELECT COUNT(salary)
    FROM employees;
    

    This counts the number of non-NULL values in the salary column.

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 WHERE clause can be used to filter rows based on specific conditions.

No comments:

Post a Comment