SQL Server COUNT


This entry is part 1 of 4 in the series SQL Count

In T-SQL, COUNT returns the number of items in a group. COUNT works like the COUNT_BIG function. The only difference between the two functions is their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value. COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.

The Microsoft Press book T-SQL Querying by Ikzik Ben-Gan et al has an example table called Orders that you could use in a non-production server. We could use this table to illustrate the basics of COUNT. The script below creates the table and populates it with a bit of data.

1CREATE TABLE dbo.Orders(
2  orderid INT     NOT NULL,
3  custid  CHAR(5)     NULL);
4go
5INSERT INTO dbo.Orders(orderid, custid) VALUES
6  (1, 'FRNDO'),
7  (2, 'FRNDO'),
8  (3, 'KRLOS'),
9  (4, 'KRLOS'),
10  (5, 'KRLOS'),
11  (6, 'MRPHS'),
12  (7, NULL   );

Here are some queries that illustrate COUNT.

1SELECT orderid, custid FROM Orders
2select count(*) from Orders
3select count(custid) from Orders
4select count(distinct custid) from Orders

Here are the results in SSMS.

  • COUNT(*) includes NULLs. All the rows.
  • COUNT(custid) ignores NULLS. All the rows except where custid is NULL
  • COUNT(DISTINCT custid) also ignores NULLs. All of the different customer ids not including NULLs

Here below is a query using GROUP BY.

1SELECT custid, COUNT(custid) as Num_Orders
2  FROM Orders
3  GROUP BY custid

Below is a screenshot of the results.

Series NavigationSQL Server COUNT DISTINCT >>