User-Defined Functions «Prev  Next»

Lesson 4Functions returning a number, text, or date value
ObjectiveCreate and call Oracle 26ai PL/SQL functions that return NUMBER, VARCHAR2, or DATE values.

Create PL/SQL Functions That Return Number, Text, or Date Values

A PL/SQL function computes a result that its caller can use in an expression. In Oracle AI Database 26ai, a standalone stored function belongs to a database schema and can be called by name after it has compiled successfully. This lesson creates three functions: one formats text, one calculates a number, and one returns a date seven days after its input.

Each function has one declared result type. Returning a sentence that contains a number still produces one text value. Choosing the appropriate type lets the caller sort, compare, calculate, or format the result without first extracting information from a sentence.

The scripts below use SQL*Plus. Run them in a practice schema with the CREATE PROCEDURE system privilege, which also authorizes creating standalone functions in that schema. OR REPLACE replaces an existing function with the same name, so check the names before submitting a script. The displayed results are expected examples; these scripts have been reviewed against Oracle 26ai documentation but have not been executed on an Oracle instance for this lesson.

Understand the function definition and its return value

The function header identifies its name, parameters, and return type. A parameter is a named placeholder such as p_zipcode; an argument is the value supplied by a call. The examples use IN parameters because they receive input and return their results through the function value.

PL/SQL function header, input parameter, return type, declarations, executable statements, and SQL*Plus submission in Oracle 26ai.

Figure 1. Define an Oracle 26ai PL/SQL function. The header names the input and result type; BEGIN starts executable statements. The slash is a SQL*Plus submission command.

Figure 1 shows the parts of a definition. It is an anatomy diagram; use the complete script below when creating the function. IS or AS introduces the implementation, optional declarations come next, and BEGIN starts executable statements. A simple function does not need an extra nested DECLARE block. The number example later demonstrates a local constant declared before BEGIN.

The header's RETURN VARCHAR2 clause declares the result type. Inside the body, RETURN expression; evaluates an expression, supplies that value to the caller, and ends the function call. Every path that completes normally must return a value. A path that raises an exception instead reports failure to the caller.

Write these result declarations as RETURN VARCHAR2, RETURN NUMBER, or RETURN DATE, without adding a length, precision, or scale. A local variable declaration has different rules: l_zip VARCHAR2(10); allocates space for the formatted text. These examples also use unconstrained parameter declarations such as p_zipcode IN VARCHAR2.

PL/SQL supports parameter modes beyond IN, but Oracle recommends avoiding OUT and IN OUT parameters for functions. Keep these SQL-callable examples focused on receiving arguments and returning a result. See Oracle's CREATE FUNCTION reference and parameter-mode documentation for the detailed rules.

Return text: format supplied ZIP-code digits

Postal codes are identifiers, so the first example accepts and returns VARCHAR2. Passing a numeric argument can lose leading zeros before the function receives it. Keep values such as '021081234' as text throughout the call.

The function's policy is explicit: preserve five supplied digits, insert a dash into nine supplied digits, preserve an already formatted five-plus-four string, and return NULL for missing input. Reject other shapes. It does not trim spaces, invent an extension, or determine whether a postal address exists. Preserving five digits instead of appending an invented extension is a design choice for this example, not an Oracle 26ai language change.

Five formatting cases for a text-returning PL/SQL function: null, five digits, nine digits, formatted input, and an invalid input error.

Figure 2. Apply the formatting rules. Preserve five supplied digits, insert a dash into nine supplied digits, retain an existing five-plus-four format, return NULL for NULL, and reject invalid shapes.

Create the text-returning function

CREATE OR REPLACE FUNCTION format_zip_code(p_zipcode IN VARCHAR2)
  RETURN VARCHAR2
IS
BEGIN
  IF p_zipcode IS NULL THEN
    RETURN NULL;
  ELSIF LENGTH(p_zipcode) = 5
        AND REGEXP_LIKE(p_zipcode, '^[0-9]{5}$', 'c') THEN
    RETURN p_zipcode;
  ELSIF LENGTH(p_zipcode) = 9
        AND REGEXP_LIKE(p_zipcode, '^[0-9]{9}$', 'c') THEN
    RETURN SUBSTR(p_zipcode, 1, 5) || '-' || SUBSTR(p_zipcode, 6, 4);
  ELSIF LENGTH(p_zipcode) = 10
        AND REGEXP_LIKE(p_zipcode, '^[0-9]{5}-[0-9]{4}$', 'c') THEN
    RETURN p_zipcode;
  ELSE
    RAISE_APPLICATION_ERROR(
      -20001,
      'Expected five digits, nine digits, or five digits plus a dash and four digits.'
    );
  END IF;
END format_zip_code;
/
SHOW ERRORS FUNCTION format_zip_code

The IF branches make the return paths visible. IS NULL handles missing input first. Oracle currently treats an empty VARCHAR2 string as null, so an empty string follows that branch too. The remaining branches combine an exact length with a digit pattern. Length alone would accept five letters just as readily as five digits.

In these regular expressions, ^ and $ anchor the input, [0-9] matches a digit, and {5} or {9} specifies its count. The final pattern requires five digits, a literal dash, and four digits. The explicit length checks reinforce the accepted shapes. The 'c' match parameter requests case-sensitive matching, although case makes no difference to these digit-only patterns.

For nine digits, SUBSTR(p_zipcode, 1, 5) extracts the first five characters and SUBSTR(p_zipcode, 6, 4) extracts the last four. The concatenation operator || joins those pieces with a dash. Each successful branch returns directly, so a separate local output buffer is unnecessary.

Compile and call the function in SQL*Plus

Enter the complete definition through END format_zip_code;, then put / on a separate line. In SQL*Plus, the slash submits the buffered definition. It is a client command, not a statement stored inside the function. Run SHOW ERRORS FUNCTION format_zip_code afterward to inspect compilation errors.

Oracle 26ai SQL*Plus workflow: submit a function definition, check compilation, bind text input, and call the function from SELECT.

Figure 3. Compile and call the function in SQL*Plus. SHOW ERRORS checks compilation. With zip_input bound to text 967531234, the SELECT is expected to return 96753-1234; the diagram is illustrative, not an execution record.

A successful compilation is expected to show no errors. If SQL*Plus reports that the function was created with compilation errors, inspect the reported line and position, correct the definition, and submit it again. Successful creation alone does not demonstrate correct behavior for every input.

Figure 3 calls the function using a bind variable. The following SQL*Plus commands provide the complete setup for that call. VARIABLE creates the client bind variable; EXECUTE assigns its text value. The colon in the query identifies the bind variable.

VARIABLE zip_input VARCHAR2(10)
EXECUTE :zip_input := '967531234';

SELECT format_zip_code(:zip_input) AS zip
FROM dual;

Expected ZIP value: 96753-1234. The result comes from the SELECT expression. This query does not need DBMS_OUTPUT or SET SERVEROUTPUT ON. DUAL supplies a convenient single row for these expression examples.

A function argument can also be a literal or a compatible column expression. The following query checks several accepted inputs together. Each expression has an alias so the result is easy to identify.

SELECT format_zip_code('96753') AS five_digits,
       format_zip_code('967531234') AS nine_digits,
       format_zip_code('021081234') AS leading_zero,
       format_zip_code('96753-1234') AS already_formatted,
       NVL(format_zip_code(NULL), '<NULL>') AS null_input
FROM dual;
Expected text results
ColumnExpected value
FIVE_DIGITS96753
NINE_DIGITS96753-1234
LEADING_ZERO02108-1234
ALREADY_FORMATTED96753-1234
NULL_INPUT<NULL>, supplied by NVL in the calling query

The null marker is display text added by the query. The function itself returns an actual null for that case. This distinction matters when another expression tests the result with IS NULL.

Make invalid input visible

The final branch calls RAISE_APPLICATION_ERROR with application error number -20001. The caller receives an error rather than an apparently successful value. Run these negative cases separately from the successful query: an unhandled exception from any expression would fail its SQL statement.

SELECT format_zip_code('ABCDE') FROM dual;
SELECT format_zip_code('123456') FROM dual;
SELECT format_zip_code(' 96753') FROM dual;
SELECT format_zip_code('12345678901') FROM dual;

Each statement is expected to raise ORA-20001. They cover letters, an unsupported length, leading whitespace, and an overlong value. The exception is intentional; do not hide it with a catch-all handler that returns null. Missing input and invalid input have different meanings in this function's contract.

Return a NUMBER: calculate a circle's area

A numeric result should remain numeric when callers need to calculate with it. The next function uses the approximation 3.14159 for pi and returns the calculated area as NUMBER. It accepts zero, returns null for missing input, and rejects a negative radius.

CREATE OR REPLACE FUNCTION circle_area_number(p_radius IN NUMBER)
  RETURN NUMBER
IS
  c_pi CONSTANT NUMBER := 3.14159;
BEGIN
  IF p_radius IS NULL THEN
    RETURN NULL;
  ELSIF p_radius < 0 THEN
    RAISE_APPLICATION_ERROR(-20002, 'Radius must be zero or greater.');
  END IF;

  RETURN c_pi * p_radius * p_radius;
END circle_area_number;
/
SHOW ERRORS FUNCTION circle_area_number

The constant c_pi belongs to the declarative region between IS and BEGIN. After the input checks, one return statement computes the result. The negative-radius branch raises ORA-20002, so that path does not complete normally and does not need to return a number.

SELECT circle_area_number(5) AS area,
       ROUND(circle_area_number(5), 2) AS rounded_area
FROM dual;

Expected numeric values: AREA = 78.53975 and ROUNDED_AREA = 78.54. Client column spacing and decimal separators can vary. The values reflect the stated approximation of pi. The query applies ROUND to the returned number without parsing text or changing the stored function.

Use consistent units: a radius measured in meters produces an area in square meters. Keep the unrounded result when later calculations need it, and round at the appropriate presentation or business-rule boundary. Test a zero radius, a null radius, and a negative radius as well as the positive example.

If a screen needs a sentence describing the area, format that sentence in the calling layer. Concatenating a radius and an area into a VARCHAR2 message still returns one string. It does not return independent numeric and text values.

Return a DATE: add seven calendar days

The date example accepts a DATE, adds seven days, and returns a DATE. Oracle DATE values include a time of day to the second but do not contain a time zone. Adding a whole number of days preserves the input's time of day.

CREATE OR REPLACE FUNCTION one_week_later(p_start_date IN DATE)
  RETURN DATE
IS
BEGIN
  RETURN p_start_date + 7;
END one_week_later;
/
SHOW ERRORS FUNCTION one_week_later

Use a DATE literal to make the example input independent of the session's default date-string format. Apply TO_CHAR in the calling query to choose an explicit display format:

SELECT TO_CHAR(
         one_week_later(DATE '2026-11-29'),
         'YYYY-MM-DD HH24:MI:SS'
       ) AS next_week
FROM dual;

Expected display: 2026-12-06 00:00:00. The DATE literal supplies midnight. The function returns a DATE value, and TO_CHAR converts that result to VARCHAR2 for this display. A different display format would not change the underlying date returned by the function.

A null input produces null through date arithmetic. This function adds seven calendar days; it does not skip weekends or holidays. It also does not implement time-zone-aware scheduling. When the caller needs date comparisons or further date arithmetic, use the function's DATE result directly and format it only when presenting it.

Use the returned value in a PL/SQL block

A PL/SQL caller can assign a function result to a compatible variable. Here, l_zip holds the formatted text, and DBMS_OUTPUT.PUT_LINE buffers that text for the client to retrieve and display.

SET SERVEROUTPUT ON

DECLARE
  l_zip VARCHAR2(10);
BEGIN
  l_zip := format_zip_code('967531234');
  DBMS_OUTPUT.PUT_LINE(l_zip);
END;
/

Expected displayed text: 96753-1234. SET SERVEROUTPUT ON tells SQL*Plus to retrieve and display buffered output. The assignment receives the function's return value before the display procedure runs. If output display is disabled, the function can still return a value successfully.

The receiving variable must accommodate the result. The ten-character declaration fits five digits, a dash, and four digits. A variable that is too small can raise an assignment error even when the function has generated the intended string.

Check compilation, behavior, and SQL use separately

Use three checks when developing a stored function. First, compile the complete definition and inspect SHOW ERRORS. Second, call it with ordinary inputs and compare the returned values. Third, exercise the boundaries: nulls, zero or empty input where relevant, and deliberately invalid values. A clean compilation cannot prove that the chosen business rules are correct.

Before putting a function into a query over many rows, define what should happen when one row has invalid input. In the ZIP example, an invalid value raises an exception and can fail the query. That is useful for exposing bad data, but callers must choose their validation and error-handling strategy deliberately.

SQL-invoked PL/SQL functions have restrictions on parameters and side effects, in addition to their result types. These examples compute from their inputs and perform no DML, DDL, or transaction control. Keep that pattern for this lesson and consult Oracle's rules for functions invoked by SQL before adding database changes inside a function.

Reusable logic does not automatically make a query faster. Evaluate the SQL execution plan and workload before making performance claims, and do not depend on a function being called exactly once per result row. The examples here teach types, return paths, and calling syntax.

Function Returning Value: Exercise

For each example, identify the declared result type, a normal return path, and the treatment of missing input. Then change one argument in a practice call and predict its result before running it. For the numeric function, explain why the caller can apply ROUND directly. For the date function, explain why formatting belongs in the query rather than the return declaration.

Function Returning Value - Exercise

The next lesson examines functions that return a Boolean value. Oracle 26ai supports SQL BOOLEAN as well as PL/SQL BOOLEAN; its examples and null behavior belong to that next topic.

SEMrush Software 4 SEMrush Banner 4