Saturday, March 8, 2014

SQL COUNT Example

COUNT returns the number of rows in a select statement (Also note that it doesn't consider null values),

Note : I'll be using the AdventureWorks2008R2 sample database which can be downloaded from here,

http://msftdbprodsamples.codeplex.com/releases/view/59211


Example 1,

/* By using the * we return the number of records in the Sales.Customer table */
select

count(*)

from Sales.Customer;



Example 2,

/* By using StoreID inside the COUNT() function we return the number of store id's in the Sales.Customer table */

select

count(StoreID)

from Sales.Customer;


Example 3,
  /* By using "DISTINCT StoreID" inside the COUNT() function we return the unique number of store id's in the Sales.Customer table */

select

count(distinct StoreID)

from Sales.Customer;
Note: From a performance point of view it is better to use 1 instead of * inside the COUNT function.

0 comments:

Post a Comment