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.

CREATE TABLE sales_record(
itemId INT,
itemName VARCHAR2(20),
qty INT
);

INSERT ALL
INTO sale_record VALUES(22, 'Notebook', 12)
INTO sale_record VALUES(89, 'Pencil', 2)
INTO sale_record VALUES(22, 'Notebook', 12)
INTO sale_record VALUES(89, 'Pencil', 2)
INTO sale_record VALUES(89, 'Pencil', 10)
INTO sale_record VALUES(66, 'Pen', 56)
INTO sale_record VALUES(75, 'Geometry Box', 90)
INTO sale_record VALUES(66, 'Pen', 56)
SELECT * FROM DUAL;

Output:

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

As we can see in the table above a lot of records have inserted multiple times. This can cause a lot of issue in production tables when aggregation need to be performed on the table and will lead to inflated values. Now lets count the distinct records in the table. The following query counts all the distinct records in the sales_record table:

SELECT COUNT(*) FROM (
SELECT DISTINCT * FROM sales_record
);

Output:

If we run the inner subquery.

SELECT DISTINCT * FROM sales_record;

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....