w3resource
SQL Tutorial

SQL COUNT() with distinct

COUNT() function with distinct clause

SQL COUNT() function with DISTINCT clause eliminates the repetitive appearance of the same data. The DISTINCT can come only once in a given select statement.

Syntax :

COUNT(DISTINCT expr,[expr...])

Example :

To get unique number of rows from the 'orders' table with following conditions -

1. only unique cust_code will be counted,

2. result will appear with the heading "Number of employees",

the following SQL statement can be used :

SELECT COUNT ( DISTINCT cust_code ) AS "Number of employees" 
FROM orders;

Sample table : orders

Output :

Number of employees
-------------------
                 25

Pictorial Presentation:

SQL COUNT WITH DISTINCT clause

SQL COUNT( ) with All

In the following, we have discussed the usage of ALL clause with SQL COUNT() function to count only the non NULL value for the specified column within the argument. The difference between ‘*’(asterisk) and ALL are, '*' counts the NULL value also but ALL counts only NON NULL value.

Example:

To get data of number of valid 'grade' from the 'customer' table with the following condition -

1. every customer must be a valid grade,

the following SQL statement can be used :

SELECT COUNT( ALL grade )
FROM customer;

Sample table: customer


Output :

COUNT(ALLGRADE)
---------------
             25

Note: Outputs of the said SQL statement shown here is taken by using Oracle Database 10g Express Edition.

Here is a slide presentation of all aggregate functions.

Previous: COUNT Function
Next: COUNT with Group by