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

Pictorial Presentation:


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.


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 :

FROM customer;

Sample table: customer

Output :


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

Follow us on Facebook and Twitter for latest update.

SQL: Tips of the Day

SET versus SELECT when assigning variables?

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one).
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value).
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Ref : https://bit.ly/3FiZ2KJ