Tuesday, January 15, 2013

DISTINCT and COUNT

Examples Statement:
SELECT JOB_ID FROM EMPLOYEES;
This statement returns 107 rows (number of records of EMPLOYEES).


However, the result has duplicate JOB_IDs. When we want to display distinct JOB_ID, we use keyword DISTINCT on the SELECT statement.
Examples Statement:
SELECT DISTINCT JOB_ID FROM EMPLOYEES;


The result displays 19 different JOB_ID.

When we want to know number of records of a table, we use the COUNT keyword. We could use an asterisk or a name of column with the COUNT keyword.
Examples Statement:
SELECT COUNT(EMPLOYEE_ID) FROM EMPLOYEES;


Examples Statement:
SELECT COUNT(*) FROM EMPLOYEES;


We could use DISTINCT for COUNT when we want to know number of different values on the table.
Examples Statement:
SELECT COUNT(MANAGER_ID) FROM EMPLOYEES;


This statement returns 106 while the statement COUNT(*) returns 107. The reason is that COUNT(*) will 
count NULL values also.
Examples Statement:
SELECT COUNT(DISTINCT MANAGER_ID) FROM EMPLOYEES;


The result is 18 – the number of different MANAGER_ID on EMPLOYEES (including NULL values).



No comments:

Post a Comment