Skip to content
Advertisement

Sum up all values from a list PLSQL

I want to sum up all values from a INDEX BY TABLE list.

In the list there are values like this:

24000, 4500, 7890 and so on.

This is the code:

Advertisement

Answer

Lets assume that you have an associated array and you want to sum up the values within it. And, lets also assume that the associative array’s index is sparse.

So, if we have the test data:

(Note: the IDs do not go 1, 2, 3.)

then we populate the associative array with the code:

To perform the sum then we need to iterate over the associative array. This cannot be done in SQL as an associative array is a PL/SQL only data type so you have two options:

  1. Convert the PL/SQL associative array to a collection in the SQL scope and use an SQL statement to sum the values; or
  2. Iterate over the associative array in PL/SQL.

This is the second option and will use .FIRST and .NEXT(index) properties of the associative array to iterate over the sparse array (whereas, using a counter and incrementing by 1 will fail when the array is sparse):

Which outputs:

36390

db<>fiddle here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement