PL/SQL Parameters   «Prev  Next»

Lesson 6Function parameters and RETURN
ObjectiveUse IN parameters and the RETURN statement to define and invoke an Oracle 26ai PL/SQL function, and distinguish its result from a procedure's OUT parameters.

PL/SQL Function Parameters and the RETURN Statement in Oracle 26ai

A PL/SQL function accepts arguments, performs an operation, and returns a value that its caller can use in an expression. The function heading declares the result's data type. A RETURN statement in the body supplies the actual value and finishes that invocation. Keeping these two uses of RETURN separate makes function definitions much easier to read.

In the previous lesson, the do_address procedure constructed an address line and delivered it through an OUT parameter. Here, you will convert that task into a function and use its result in both SQL and PL/SQL. A second example explores optional arguments, null results, and validation. Neither example requires a customer or sales table.

Function results versus procedure outputs

Functions and procedures are named PL/SQL subprograms. Both can receive input, declare local variables, and execute statements. Their interfaces differ: a function declares a return type and can supply a value within an expression; a procedure has no function-result type, although it can deliver values through OUT and IN OUT parameters.

Two interfaces for producing an address line
QuestionProcedureFunction
How is the result exposed?An OUT parameter receives the constructed text.The function result is the constructed text.
How does the caller receive it?Pass a writable variable in the output position.Assign the invocation's result or use it in a suitable expression.
What does the heading declare?The output parameter and its type.A RETURN clause specifying the result type.

For these examples, use functions with IN parameters and one clear result. PL/SQL permits functions with OUT or IN OUT parameters, but Oracle recommends avoiding that design. This is different from claiming that such declarations are universally illegal. The recommendation keeps the function's main result easy to identify. See Oracle's Subprogram Parameters.

Choose the interface around the operation. Formatting supplied strings is naturally expressed as a function. An operation that updates several related records and reports multiple outcomes may be clearer as a procedure. Neither the presence of parameters nor the existence of useful output, by itself, determines which kind of subprogram you should write.

Distinguish the RETURN clause from the RETURN statement

In a function heading, RETURN VARCHAR2 declares the type of result callers should expect. It does not return any text. In the executable body, RETURN l_address; evaluates the expression and returns its value. That statement ends the function call immediately; execution does not continue to the next statement in the function.

A scalar function needs a compatible returned expression on every normal completion path. An exception represents failure rather than a successful return. A procedure can use a bare RETURN; to exit early, but cannot return an expression through that statement. These rules are documented in Oracle's RETURN statement reference.

For example, a function declared to return NUMBER should produce a numeric result, not a text label that the caller must convert. Matching the result's meaning to its declared type reduces ambiguity. A displayed value and its type are separate concerns: a client may format a number with a currency symbol without changing the function into a character-returning function.

Convert the address procedure into a function

The new function is named format_address_line, so it can coexist with the earlier do_address procedure. This example formats non-null city and state inputs and optionally appends a postal code. It does not check postal validity or retrieve an address from a database. Its purpose is to demonstrate how a computed value crosses the function interface.

The conversion requires four changes: remove the formal output parameter, declare a VARCHAR2 result in the heading, construct the address in a local variable, and return that variable. The city, state, and optional postal code remain input parameters.

CREATE OR REPLACE FUNCTION format_address_line (
    p_city        IN VARCHAR2,
    p_state       IN VARCHAR2,
    p_postal_code IN VARCHAR2 DEFAULT NULL
) RETURN VARCHAR2
AS
    l_address VARCHAR2(200);
BEGIN
    l_address := TRIM(p_city) || ', ' || UPPER(TRIM(p_state));

    IF TRIM(p_postal_code) IS NOT NULL THEN
        l_address := l_address || ' ' || TRIM(p_postal_code);
    END IF;

    RETURN l_address;
END format_address_line;
/

The first assignment removes surrounding spaces from the city and state, uppercases the state, and joins the two parts. The IF statement adds the postal code when supplied. Both paths then reach the same RETURN statement. Reading the function from its inputs to that final statement reveals the whole calculation without requiring knowledge of a sample schema.

The local variable has a length because it needs storage for the constructed string. The heading uses RETURN VARCHAR2, not RETURN VARCHAR2(200). Oracle does not allow a direct length, precision, or scale specification on that return-type declaration. The example's local capacity of 200 is a design choice for these inputs, not a universal limit for postal addresses. See CREATE FUNCTION.

AS introduces the function definition; IS could be used instead. Local declarations belong before BEGIN, without a separate DECLARE keyword. In contrast, an anonymous caller block uses DECLARE before its local declarations. A local result variable is helpful here, but functions can also return a calculated expression directly.

Create the function in a practice schema

Creating a standalone function in your own schema requires the CREATE PROCEDURE system privilege. Despite its name, that privilege also covers this function creation. Use a practice schema, and remember that OR REPLACE replaces an existing function with the same name there. It does not convert the separately named address procedure into the new function.

Run the creation script before the caller examples. In SQL*Plus or SQL Developer's script mode, the slash on a separate line submits the stored PL/SQL unit. It is a client script convention, not a statement inside the function. The code is complete for the illustrated formatting task; the expected outputs below are values to compare when you run it.

Use the function in a SQL expression

After creating the function, call it in a SELECT expression. This query supplies all three arguments positionally, matching their declaration order. The column alias gives the returned text a readable name in the result set.

SELECT format_address_line('Portland', 'or', '97205') AS address_line
FROM dual;

Expected value in ADDRESS_LINE:

Portland, OR 97205

The function does not print this line. It supplies a value to the SELECT expression, and the SQL client displays the query result. DUAL is used here as a familiar way to demonstrate one expression without introducing a table of addresses; this example does not claim that every Oracle 26ai SELECT expression requires DUAL.

A useful function interface makes the calculation reusable. The same formatting logic could be applied to city and state columns in a real query, provided the function meets the requirements for that SQL context. That is a potential application, not an assumption that a particular customer table exists in your schema.

Assign the result in PL/SQL

A PL/SQL caller can store the result with the assignment operator. Here, named notation identifies the two required inputs and omits the optional postal code. The caller variable has its own name and storage capacity.

SET SERVEROUTPUT ON
DECLARE
    l_result VARCHAR2(200);
BEGIN
    l_result := format_address_line(
        p_city  => 'Portland',
        p_state => 'or'
    );
    DBMS_OUTPUT.PUT_LINE(l_result);
END;
/

Expected displayed line:

Portland, OR

Follow the order: the caller invokes the function, the function returns the constructed string, the assignment stores it in l_result, and the caller prints it. The local l_address inside the function and l_result in the caller are separate variables. They do not need matching names to exchange the result.

SET SERVEROUTPUT ON enables client display of DBMS_OUTPUT messages. It has no role in calculating or returning the string. If the caller omitted the PUT_LINE statement, it could still use l_result in subsequent PL/SQL logic. A missing printed line is therefore not sufficient evidence that a function returned no value.

Understand inputs, defaults, and explicit NULL

The formal names p_city and p_state belong to the function definition. The literals supplied by a call are actual arguments. Named notation places the formal name on the left of => and the supplied expression on the right. IN is the default mode, but writing it explicitly makes the examples' interfaces easier to scan.

A default applies when an optional argument is omitted. Explicitly supplying NULL does not ask Oracle to substitute the default. In the address example, the default itself is NULL, so those two calls happen to behave alike. A non-null default makes the distinction visible, as the numeric example below shows.

Optionality and validation answer different questions. An optional argument may be left out; a required argument must be supplied, but its supplied value can still be null. The address function assumes usable city and state strings. If a real application's rules reject missing cities, the function needs an explicit check rather than relying on the absence of a default to enforce that business rule.

Return a value, return NULL, or raise an exception

The following independent function calculates a discounted price. Its documented policy is: reject a known negative price or an out-of-range discount; return NULL if either input is unknown; otherwise return the rounded amount. The default discount is ten percent. Rates are fractions, so 0.20 represents twenty percent.

CREATE OR REPLACE FUNCTION discounted_price (
    p_price IN NUMBER,
    p_rate  IN NUMBER DEFAULT 0.10
) RETURN NUMBER
AS
BEGIN
    IF p_price < 0 THEN
        RAISE_APPLICATION_ERROR(-20001, 'Price must not be negative.');
    END IF;

    IF p_rate < 0 OR p_rate > 1 THEN
        RAISE_APPLICATION_ERROR(-20002, 'Discount rate must be between 0 and 1.');
    END IF;

    IF p_price IS NULL OR p_rate IS NULL THEN
        RETURN NULL;
    END IF;

    RETURN ROUND(p_price * (1 - p_rate), 2);
END discounted_price;
/

The early RETURN NULL is deliberate: it represents an unknown result under this function's policy. The final RETURN computes a known result. The validation branches raise exceptions instead of returning a price. A failure cannot accidentally look like a successful zero-price calculation.

These choices are specific to this teaching example. A different application might reject null inputs as invalid rather than return null. Decide and document that policy before choosing the implementation. Do not silently convert every exception to zero or NULL, because doing so would make an invalid rate indistinguishable from a valid result or an intentionally unknown value.

SELECT discounted_price(100, 0.20) AS explicit_rate,
       discounted_price(100)       AS default_rate,
       discounted_price(100, NULL) AS unknown_rate
FROM dual;
Expected numeric results
EXPLICIT_RATEDEFAULT_RATEUNKNOWN_RATE
8090NULL

A client may display a null field as blank. That is presentation, not a zero result. The function returns NUMBER, so the client also controls whether 80 appears with decimal places. Keep display formatting separate from testing the underlying numeric value.

To inspect the error policy separately, try a price of -1 or a rate of 1.20 in a practice call. Those inputs should raise the corresponding application error. Do not combine an intentionally invalid invocation with the successful comparison query and expect every expression to produce an ordinary result.

Check every normal completion path

Falling through the end of a scalar function is not equivalent to RETURN NULL. Oracle can issue warning PLW-05005 when a function has a path without a returned value. Review branches, loops, and exception handlers for that possibility. A handler that catches an error and then reaches the end without returning or raising still leaves the function without a successful result.

For discounted_price, the path review is short: an invalid known input raises; an unknown input returns null; valid known inputs reach the arithmetic return. In the address function, the optional append branch rejoins the path to its single final return. This kind of review is more useful than counting RETURN statements: one can be sufficient, and several can also be correct.

SQL-callable functions must control side effects

A SQL-compatible result type is only part of SQL-callability. Oracle also restricts side effects in the function and subprograms it invokes. A function called by SELECT cannot modify database tables. Ordinary SQL-invoked functions cannot execute transaction control such as COMMIT. Calls from DML have additional restrictions concerning tables modified by the invoking statement. See PL/SQL functions that SQL statements can invoke.

Both examples calculate from their arguments and use no table writes or transaction control. Keep that property when experimenting. Adding an INSERT for logging or a COMMIT copied from a procedure can change whether a function is suitable for the query that calls it. Renaming a procedure and adding RETURN is not a complete SQL-callability review.

Do not use an autonomous transaction merely to bypass those restrictions in a formatting or pricing function. Likewise, do not add DETERMINISTIC or RESULT_CACHE just because the function appears simple. Such declarations need their own correctness and performance review. This lesson's goal is an understandable result-producing interface, not an untested optimization promise.

Review the function and its callers

Test the interface as well as the calculation. For format_address_line, compare supplied and omitted postal codes and check trimming and state capitalization. For discounted_price, compare the omitted rate with explicit NULL, zero, and one. Also test the rejected inputs separately. These cases expose assumptions that a single successful call cannot reveal.

When maintaining the code, keep formal names stable for named callers and argument order stable for positional callers. Ensure receiving variables can hold the result. A correctly calculated string can still be too large for the caller's destination. Changes to a result type or input policy deserve the same review as changes to the function body.

You can now identify the result type in a function heading, follow input arguments into the calculation, and locate the statement that returns control and a value. Use a function when its result belongs naturally in an expression, and retain a procedure when its output parameters or action-oriented interface better describe the task. The next lesson applies parameter concepts to PL/SQL cursors.


SEMrush Software 6 SEMrush Banner 6