Stored Aggregate Functions

Stored Aggregate Functions allow users to create custom aggregate functions that process a sequence of rows and return a single summary result.

Aggregate functions are functions that are computed over a sequence of rows and return one result for the sequence of rows.

Creating a custom aggregate function is done using the CREATE FUNCTION statement with two main differences:

  • The addition of the AGGREGATE keyword, so CREATE AGGREGATE FUNCTION

  • The FETCH GROUP NEXT ROW instruction inside the loop

  • Oracle PL/SQL compatibility using SQL/PL is provided

Standard Syntax

CREATE AGGREGATE FUNCTION function_name (parameters) RETURNS return_type
BEGIN
      ALL types of declarations
      DECLARE CONTINUE HANDLER FOR NOT FOUND RETURN return_val;
      LOOP
           FETCH GROUP NEXT ROW; // fetches next row FROM TABLE
           other instructions
      END LOOP;
END

Stored aggregate functions were a 2016 Google Summer of Code project by Varun Gupta.

Using SQL/PL

Examples

First a simplified example:

A non-trivial example that cannot easily be rewritten using existing functions:

SQL/PL Example

This uses the same marks table as created above.

See Also

This page is licensed: CC BY-SA / Gnu FDL

Last updated

Was this helpful?