SQL Server COUNT DISTINCT


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

You can count the number of unique values in a column with COUNT DISTINCT.

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. You can run this in a non-production server.

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

How many unique customers are there? You can see three: FRNDO, KRLOS, and MRPHS.

SELECT COUNT(DISTINCT custid) AS 'number of unique customers'
FROM dbo.Orders;

Below is a screenshot of the results in SSMS.

Series Navigation<< SQL Server COUNTSQL Server Count Duplicates >>

Leave a Reply