T-SQL Tutorial

SQL Server COUNT


In SQL Server, the COUNT function is commonly used to count the number of rows in a table or the number of rows that meet a specific condition in a query. Here's an example of how you can use COUNT in a SQL Server query to count rows and exclude NULL values.

Let's say you have a table named YourTable with a column named YourColumn and you want to count the non-NULL values in that column. You can use the following query:


COUNT column

SELECT
COUNT(YourColumn) AS NonNullCount
FROM YourTable;

This query will return the count of non-NULL values in the YourColumn column of the YourTable table. The COUNT function, in this case, only counts the rows where the specified column is not NULL.


COUNT total rows

If you want to count all rows in the table, regardless of whether the column is NULL or not, you can use the following query:

SELECT
COUNT(*) AS TotalCount
FROM YourTable;

This query will return the total number of rows in the YourTable table.


COUNT with condition

If you want to count rows based on a certain condition while excluding NULL values, you can use the CASE statement inside the COUNT function. Here's an example:

SELECT
COUNT(CASE WHEN YourColumn IS NOT NULL THEN 1 END) AS CountWithCondition
FROM YourTable;

In this query, the CASE statement checks if the YourColumn is not NULL, and if it's not, it returns 1. The COUNT function then counts the non-NULL values based on the condition.

These examples should give you a good starting point for using the COUNT function in SQL Server queries to count rows and handle NULL values based on your specific requirements.

See also: T-SQL Functions -> Avg -> Max -> Min -> Sum