Method to Count Distinct Values

Method 1: Using DISTINCT Keyword

We can make use of the DISTINCT keyword to count the distinct values in the table. In the following query we have made use of subquery to first retrieve the distinct records from the table and later used that along with count() function to get the distinct count:

SELECT COUNT(*) AS distinct_cnt FROM (
SELECT DISTINCT * FROM sample
);

Output:

Explanation: We get the output according to the above query.

Method 2: Using GROUP BY Clause

We can make use of the GROUP BY clause to group all the duplicate values into one record. In the following query we have made the use of subquery to first group all the records to make them unique and later used them to get the distinct count:

SELECT COUNT(*) AS distinct_cnt FROM (
SELECT val1, val2, val3 FROM sample
GROUP BY val1, val2, val3
);

Output:

Explanation: We get the output according to the above query.

How to Count Distinct Values in PL/SQL?

PL/SQL is a procedural language designed to allow users to combine the power of procedural language with Oracle SQL. PL/SQL includes procedural language elements such as conditions and loops and can handle exceptions (run-time errors). It also allows the declaration of constants and variables, procedures, functions, packages, types and variables of those types, and triggers.

In this article, we are going to see how we can count distinct values in PL/SQL.

Similar Reads

Setting Up Environment

Let’s create a sample table and insert some records in it....

DISTINCT Keyword in PL/SQL

The DISTINCT keyword is a keyword which is used to fetch unique or distinct records from a table....

COUNT() function in PL/SQL

The COUNT() function is used to count the non-null records from a table...

GROUP BY Clause in PL/SQL

The GROUP BY clause is used to collect data from various records by group them using one or more columns....

Method to Count Distinct Values

Method 1: Using DISTINCT Keyword...

Technical Example

Let’s understand the above methods in this examples in detail manner. Also, create an table and insert some data inside it. The following query creates a sales_record table....

Conclusion

Overall, after reading the whole article now you have good understanding about how to count distinct values through various methods like Using DISTINCT and Using GROUP BY method. In this article we have implemented various method and saw the example along with the output and their explanations. Now you can easily use these method and insert records into the tables easily....

Contact Us