Labels

Wednesday, 24 October 2012

SQL - 'COUNT' with 'DISTINCT'


Consider you have an employee table which contains the following records:

Select * from emp
empname
empid
sal
mgr_id
sundar
101
100
505
sund1
102
100
506
sund2
103
10
507
sund3
104
1000
103
sund4
105
2000
509
Sundar1
NULL
NULL
NULL
Sundar2
NULL
NULL
NULL

And of course, you very well knew that count(*) returns the number of records in a table.
For example: Select count(*) from emp .
It returns ‘7’

Suppose if you want to get the Unique number of records in a column of table, you may use distinct.
Select distinct(empid) from emp
But problem here is that, distinct consider ‘Null’ values as well. So it returns below 6 records.
empid
101
102
103
104
105
NULL

The best way to find out the unique records in a particular column, use 'count' instead of 'distinct'.
For example:
Select count(empid) from emp
It returns ‘5’ and ignores ‘Null’ values.


No comments:

Post a Comment