Click here to Skip to main content
15,868,164 members
Articles / Programming Languages / SQL
Tip/Trick

COUNT of DISTINCT Rows in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.13/5 (7 votes)
26 Nov 2010CPOL 79.2K   6   4
COUNT of DISTINCT Rows in SQL Server
SQL Server does not support COUNT(DISTINCT *). For example, the below query fails.

SELECT COUNT(DISTINCT *) FROM Employees


The error message generated is:

XML
Incorrect syntax near '*'


Instead, use the below query:

SELECT COUNT(*) FROM (SELECT DISTINCT * FROM Employees) Emp


Note: This is specifically useful when you want 'DISTINCT *' - without coloumn name(s)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
Ravikiran Malladi is a senior software professional in Microsoft technologies. He has global IT experience of over 10 years and has compulsive habit of writing tools, particularly for the projects he works on. He has vast experience in the roles of senior developer, technical analyst, technical architect besides in technical lead roles.

His hobbies include chess, music, cricket, web sites along side writing technical articles and technical blogs.

Comments and Discussions

 
GeneralMy vote of 1 Pin
kimberly wind21-Feb-13 17:52
kimberly wind21-Feb-13 17:52 
GeneralReason for my vote of 5 It works for DISTINCT but also work ... Pin
Simon Dufour1-Dec-10 3:17
Simon Dufour1-Dec-10 3:17 
Reason for my vote of 5
It works for DISTINCT but also work for any kind of subselect. If you wanted to count all the employees living in a city, you'd only have a small edit to make here. Good tip.
GeneralReason for my vote of 3 gud 1 Pin
ravindra_dhakate@rediffmail.com29-Nov-10 3:39
ravindra_dhakate@rediffmail.com29-Nov-10 3:39 
GeneralReason for my vote of 5 Good Tip. Pin
Hiren solanki29-Nov-10 2:00
Hiren solanki29-Nov-10 2:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.