Creation of user-defined functions
You can create your own functions in DB2® to simplify your queries.
There are three primary types of user-defined functions.
- Sourced functions
- Functions that are based on existing functions.
- External functions
- Functions that are developed by users.
- SQL functions
- Functions that are defined to the database by use of SQL statements only.
External user-defined functions can return a single value or a table of values.
- External functions that return a single value are called user-defined scalar functions.
- External functions that return a table are called user-defined table functions.
User-defined functions, like built-in functions or operators, support the manipulation of distinct types.

The following two examples demonstrate how to define and use both a user-defined function and a distinct type.
CREATE FUNCTION AVG(EURO)
RETURNS EURO
SOURCE SYSIBM.AVG(DECIMAL);
SELECT AVG(EUROSAL) FROM EUROEMP;
The next two examples demonstrate how to define and use an external user-defined function.
CREATE FUNCTION REVERSE(VARCHAR(100))
RETURNS VARCHAR(100)
EXTERNAL NAME 'REVERSE'
PARAMETER STYLE SQL
LANGUAGE C;
SELECT REVERSE(:CHARSTR)
FROM SYSDUMMY1;
Although you cannot write user-defined aggregate functions, you can define sourced user-defined aggregate functions that are based on built-in aggregate functions. This capability is useful in cases where you want to refer to an existing user-defined function by another name or where you want to pass a distinct type.
The next two examples demonstrate how to define and use a user-defined table function.
CREATE FUNCTION BOOKS (VARCHAR(40))
RETURNS TABLE (TITLE_NAME VARCHAR(25),
AUTHOR_NAME VARCHAR(25),
PUBLISHER_NAME VARCHAR(25),
ISBNNO VARCHAR(20),
PRICE_AMT DECIMAL(5,2),
CHAP1_TXT CLOB(50K))
LANGUAGE COBOL
PARAMETER STYLE SQL
EXTERNAL NAME BOOKS;
SELECT B.TITLE_NAME, B.AUTHOR_NAME, B.PUBLISHER_NAME, B.ISBNNO
FROM TABLE(BOOKS('Computers')) AS B
WHERE B.TITLE_NAME LIKE '%COBOL%';
