Logo 
Search:

SQL Server Articles

Submit Article
Home » Articles » SQL Server » Aggregate FunctionsRSS Feeds

COUNT Function

Posted By: Sarita Patel     Category: SQL Server     Views: 3872

This article explains COUNT function of sql server with different examples.

COUNT function is used to count particular item in a group. It returns number of items in a group.

Note that  :

COUNT(*) returns the number of items in a group including NULL values and duplicates.

COUNT(ALL expression) evaluates expression for each row in a group and returns the number of nonnull values.

COUNT(DISTINCT expression) evaluates expression for each row in a group and returns the number of unique nonnull values.

 


Syntax of COUNT Function :

COUNT ( { [ ALL | DISTINCT ] expression ] | * } )


ALL is the default. It means all values to be count.

DISTINCT means COUNT returns the number of unique nonnull values.

Expression is an expression of any type except uniqueidentifier, text, image, or ntext. Aggregate functions and subqueries are not permitted.

* means all rows should be counted to return the total number of rows in a table. COUNT(*) takes no parameters and cannot be used with DISTINCT. COUNT(*) does not require an expression parameter because, by definition, it does not use information about any particular column. COUNT(*) returns the number of rows in a specified table without eliminating duplicates. It counts each row separately, including rows that contain null values.

It returns an integer.



Examples of COUNT Funtion :

Example 1 : Using COUNT function in SELECT clause to get total records in a table

SELECT COUNT(*)

FROM   Products

Output
76

 

Above example displays the total number of records in a product table using count function. It considers all values in a group including null and duplicates.

 


Example 2 : Using COUNT function in SELECT clause to get total product in invoices table

SELECT COUNT(ProductName)

FROM   Invoices

Output
2155


Above example displays the total number of product in a invoices table using count function. It considers all values in a group including duplicate values.


 

Example 3 : Using COUNT function and DISTINCT in SELECT clause to get unique products in invoices table

SELECT COUNT(DISTINCT ProductName)

FROM   Invoices

Output
77


Above example displays the total number of unique product in a invoices table using count function. It considers all values in a group which has unique nonnull values.

  
Share: 

 
 
 

Didn't find what you were looking for? Find more on COUNT Function Or get search suggestion and latest updates.

Sarita Patel
Sarita Patel author of COUNT Function is from United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!