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.
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM table
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;
Explanation:
- expression1, expression2, … expression_n: These are expressions that are included in the GROUP BY clause
- aggregate_function: The function which will be used to aggregate the records.
- aggregate_expression: The expression whose values are to be aggregated.
- table: The table from which to count.
- conditions: The condition on which to filter the table optionally.
Example:
The following query sums the values of val2 field grouped by val1 field:
SELECT val1, SUM(val2) AS sum FROM sample
GROUP BY val1;
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.