User-Defined Functions «Prev  Next»

Lesson 2Function uses and correct syntax
ObjectiveExplain when a function is useful, identify its syntax, and distinguish PL/SQL calls from SQL expression calls.

Oracle PL/SQL Functions: Uses and Correct Syntax

A PL/SQL function is a subprogram with a declared return type. It accepts zero or more parameters and produces a return value when it completes normally. A function can also raise an exception instead of returning, and its result may be NULL when that is part of its intended behavior.

A stored function[1] makes useful logic available through a named database interface. In the Pet Store project, that logic might calculate tax or count the product entries belonging to a sale. The caller supplies arguments and uses the returned value in another operation.

This lesson explains those uses and the basic syntax for Oracle AI Database 26ai. It also distinguishes a function that can be called from PL/SQL from one that is eligible for use in a SQL expression. Those contexts have different requirements.

Standalone, Packaged, and Local Functions

A standalone stored function is a schema object created with CREATE FUNCTION. A packaged function belongs to a package; its public declaration appears in the package specification. A local function is declared within a block or another subprogram and is available within its scope.

These distinctions concern organization and visibility. They do not automatically determine whether execution happens on a client. A local function declared inside an anonymous block submitted to Oracle executes on the database server, even though it is not independently stored as a schema object.

A procedure differs because it has no function-style return value. Procedures can still pass information back through OUT parameters, and callers can invoke them through PL/SQL, SQL CALL, or suitable client interfaces. Choose a function when the operation naturally computes a value that its caller needs.

When Is a Function Useful?

A function gives a calculation or lookup a name and a defined interface. Its value is often consistency: several callers can use the same implementation instead of keeping separate versions of a business rule. A useful interface states what the inputs mean, what result is returned, and how invalid or missing inputs are handled.

PL/SQL is Oracle's procedural extension to SQL. It adds variables, branching, loops, and exception handling around data operations. However, conditional logic is not automatically a reason to write PL/SQL. A SQL CASE expression, a join, an aggregate, or a built-in function may already express the operation clearly.

Common function uses include:

  • Calculating an amount from supplied values, such as a subtotal and a tax rate.
  • Normalizing an identifier into a consistent format.
  • Returning a summarized value for a supplied key, such as the number of product entries in a sale.
  • Evaluating a reusable condition, with a clearly defined result for missing inputs.

A validation function does not enforce a rule merely because it exists. Some caller must use it and act on its result. For rules that Oracle constraints can express directly, use the appropriate constraint rather than relying on every application to remember a function call.

Recognize the Function's Main Parts

The following outline is a schematic template, not executable code. The names and comments represent material you must supply. Omit the entire EXCEPTION section when there are no handlers.

CREATE OR REPLACE FUNCTION function_name (
    p_input IN NUMBER
) RETURN NUMBER
AUTHID CURRENT_USER
IS
    -- Optional local declarations
BEGIN
    -- Executable statements
    RETURN expression;
EXCEPTION
    -- Optional exception handlers
END function_name;
/

The heading names the function, declares its parameters, and specifies the return datatype. IN is the default parameter mode; it is written explicitly here to make the interface clear. AUTHID CURRENT_USER selects invoker's rights. If AUTHID is omitted for a standalone function, the default is definer's rights.

IS starts the implementation; AS is an alternative in a standalone definition. Local variables follow IS or AS, without an additional DECLARE keyword. The executable section begins with BEGIN. END closes the function, and repeating its name helps identify what is being closed.

The slash on a separate line is a SQL*Plus or SQLcl script command that executes the buffered definition. It is not part of PL/SQL grammar. A graphical client may require script mode rather than single-statement execution.

A local function declaration starts with FUNCTION rather than CREATE OR REPLACE FUNCTION. It does not take a schema prefix or its own AUTHID clause. The template above is specifically for a standalone stored function.

A Complete Calculation Example

The following function needs no sample tables. It accepts a subtotal and a decimal tax rate, rejects null or negative inputs, and returns the calculated amount rounded to two decimal places. The rate is supplied by the caller; the example does not establish a tax policy for the store.

CREATE OR REPLACE FUNCTION lesson2_tax_amount (
    p_subtotal IN NUMBER,
    p_rate     IN NUMBER
) RETURN NUMBER
AUTHID CURRENT_USER
IS
BEGIN
    IF p_subtotal IS NULL OR p_rate IS NULL
       OR p_subtotal < 0 OR p_rate < 0 THEN
        RAISE_APPLICATION_ERROR(-20001,
            'Subtotal and rate must be nonnegative, non-null values.');
    END IF;

    RETURN ROUND(p_subtotal * p_rate, 2);
END lesson2_tax_amount;
/

SHOW ERRORS FUNCTION lesson2_tax_amount

Use a practice schema and confirm that the exercise name is available: CREATE OR REPLACE replaces an existing function of that name. Creating a function in your own schema requires the CREATE PROCEDURE system privilege. Creation in another schema requires additional privileges held by the creator.

The two uses of RETURN have different jobs. RETURN NUMBER in the heading declares the result type. The statement RETURN ROUND(...) supplies the value for this invocation and returns control to the caller. Every normally completing path must return a value; the invalid-input path instead raises an exception.

Formal parameters and the return declaration use unconstrained datatype syntax such as NUMBER. Do not write p_subtotal NUMBER(10,2) in this parameter list. A local variable may use a precision or length constraint, but the syntax rules for local variables and formal declarations are different.

Call the Function from SQL

SELECT lesson2_tax_amount(100, 0.08) AS tax_amount
FROM dual;

The expected numerical result is 8: the decimal rate 0.08 represents eight percent. Client formatting may display the number differently. The function call is an expression in the SELECT list, and the alias gives its result a useful column heading.

Call the Function from PL/SQL

SET SERVEROUTPUT ON
DECLARE
    l_tax NUMBER;
BEGIN
    l_tax := lesson2_tax_amount(100, 0.08);
    DBMS_OUTPUT.PUT_LINE('Tax: ' || l_tax);
END;
/

Here the assignment uses the returned value to set a local variable. The block then displays it through DBMS_OUTPUT. SET SERVEROUTPUT and SHOW ERRORS are client commands, not statements inside the function. Creating the function, checking compilation errors, and invoking it are separate steps.

Check More Than the Happy Path

With this contract, a zero subtotal or zero rate returns zero. A negative input or a null input raises the application error. These cases test decisions made explicitly in the code. Do not add a catch-all handler that silently returns NULL for every failure; doing so can make an unexpected error look like a valid missing result.

The values described here are expected behavior, not a transcript of a database run. When practicing, inspect compilation messages and test the boundary cases in your own environment before treating the function as ready for reuse.

A Pet Store Lookup Function

A second use is returning an aggregate for a supplied key. The next example requires the Pet Store practice schema and access to SALE_ITEM. Its local counter is an unconstrained NUMBER, so a count of 100 does not overflow a two-digit variable.

CREATE OR REPLACE FUNCTION lesson2_sale_item_count (
    p_sales_id IN NUMBER
) RETURN NUMBER
AUTHID CURRENT_USER
IS
    l_count NUMBER;
BEGIN
    SELECT COUNT(*)
    INTO l_count
    FROM sale_item i
    WHERE i.sales_id = p_sales_id;

    RETURN l_count;
END lesson2_sale_item_count;
/

SHOW ERRORS FUNCTION lesson2_sale_item_count

SELECT lesson2_sale_item_count(22) AS item_count
FROM dual;

COUNT(*) without GROUP BY produces one aggregate row. If no item matches the supplied sale identifier, the count is zero; the query does not raise NO_DATA_FOUND for that case. A null identifier also matches no rows under this equality condition and therefore returns zero.

The revised initial course fixture has three item rows for sale 22. Later exercises can change that result. This function counts sale/product entries, not units sold: the schema has no QUANTITY column. It also does not distinguish an existing empty sale from an identifier with no matching sale.

For a report covering many sales, a single grouped SQL query may be more appropriate than invoking a lookup function repeatedly. The example teaches a reusable interface, not a guarantee that wrapping an aggregate in PL/SQL improves performance.

Calling Functions from SQL: Context Matters

Eligible functions can appear in SELECT lists, suitable WHERE expressions, UPDATE SET assignments, and INSERT VALUES expressions. Eligibility depends on the function's signature, the caller's privileges, and the rules of the calling SQL statement.

Function capabilities and invocation limits
ContextWhat to remember
PL/SQL callerA function may contain data-changing statements when its context and privileges permit them. PL/SQL does not universally prohibit INSERT, UPDATE, or DELETE in function bodies.
SQL SELECT callerOrdinary functions called by a SELECT must not modify database tables. Keep these examples free of data-changing side effects.
SQL DML callerAdditional rules govern access to the table modified by the invoking statement, parallel DML, and transaction control. A function usable in one context is not automatically usable in another.
SQL signatureUse SQL-compatible argument and result types and IN-only formal parameters for ordinary SQL-expression calls.
BOOLEAN in Oracle 26aiSQL supports BOOLEAN. Eligible functions can use BOOLEAN arguments or results in SQL; the older blanket exclusion is no longer correct.
CHECK constraintA CHECK constraint cannot directly call a user-defined function. Use an allowed declarative expression for rules it can express.

The restrictions also matter when a function calls another subprogram. Moving a prohibited action into a helper does not make it permissible. Keep transaction boundaries in the calling operation for the examples in this lesson, and consult Oracle's SQL invocation rules for detailed restrictions.

PL/SQL permits OUT and IN OUT function parameters, but Oracle discourages them, and they are not suitable for ordinary SQL-expression invocation. Use input parameters and the return value here. SQL BOOLEAN support does not mean that every PL/SQL-only record or collection type can be used in every SQL expression.

SQL is declarative. Do not depend on a function being evaluated exactly once per row or in a particular order. Design functions used in expressions so their correctness does not rely on an assumed sequence of side effects.

Understand Optional Clauses Before Using Them

Several clauses affect behavior or execution, but none is required simply because a function is stored. Keep the basic definition small until you have a reason to add an option.

Do not mark the sale-item counting function DETERMINISTIC. Its answer can change when table rows change even if the supplied sale identifier stays the same. Read the DETERMINISTIC contract before using that assertion.

Benefits and Tradeoffs

Reuse and a clear interface can improve maintainability. They give callers a consistent calculation and give developers one implementation to review. Changing that implementation can still affect callers, expected results, and dependent objects; stored code does not make behavior changes harmless.

Server execution can reduce some client/server work, especially when an operation needs data already in the database. It can also add costs through repeated queries or transitions between SQL and PL/SQL. Measure the actual workload instead of assuming a stored function must outperform a direct SQL expression.

Access controls and the rights model determine who can invoke a function and what it can do. Encapsulation helps organize that design but is not an automatic security guarantee. Similarly, Oracle PL/SQL code is not automatically portable to other database products, even when its business calculation is simple.

A Syntax Review Checklist

  1. Is this a standalone function, a packaged function, or a local declaration?
  2. Do its parameters and return type use valid declaration syntax?
  3. Does each normal execution path return an appropriate value?
  4. Are null inputs, invalid values, and exceptions handled deliberately?
  5. Does the intended SQL or PL/SQL caller meet the function's invocation rules?
  6. Have you checked compilation errors and tested expected results?

Continue to the syntax for creating a stored function for a closer examination of the definition. Oracle's CREATE FUNCTION reference, parameter documentation, and 26ai release notes provide further detail.

[1]

Stored function: A function maintained in the database as a standalone schema object or within a stored package. It declares a return type and can be called from eligible PL/SQL or SQL contexts.


SEMrush Software 2 SEMrush Banner 2