SQL Server COUNT() Function

The COUNT() function in SQL Server counts the number of rows in a table or the number of non-null values in a specific column. It's a fundamental aggregate function used to summarize data.



COUNT(): Definition and Usage

COUNT() is incredibly useful for getting totals and understanding the size of your datasets. It's frequently used with the GROUP BY clause to count items within different categories. Importantly, COUNT() ignores NULL values—it only counts rows or values that actually have data.

Syntax

Syntax

COUNT(expression)
      

Parameter Values

Parameter Description
expression A column name (to count non-null values in that column) or an asterisk (*) to count all rows, even those with NULL values in the specified column. This is required.

Example

Counting Products

This example counts the number of products in the "Products" table (assuming a table named 'Products' exists with a 'ProductID' column). Rows where 'ProductID' is NULL will not be counted.

Syntax

SELECT COUNT(ProductID) AS NumberOfProducts FROM Products;
      
Output

NumberOfProducts
----------------
(The number of non-NULL ProductIDs in the Products table will be displayed here.)
      

**Note:** The example output will depend on the number of rows in your `Products` table and how many rows have a `NULL` value in the `ProductID` column. To count all rows, regardless of `NULL` values in `ProductID`, use `COUNT(*)` instead of `COUNT(ProductID)`.