| Lesson 2 | Oracle functions and procedures |
| Objective | Distinguish a function from a procedure by its interface, invocation and execution context. |
In Oracle PL/SQL, a function supplies a return value that a caller uses in an expression. A procedure performs an operation through a statement-style call and can provide results through output parameters. Both can contain calculations, decisions, loops, SQL statements and exception handling. Choose between them by considering what the caller needs and where the routine will run.
This lesson uses Oracle AI Database 26ai. The basic distinctions are established PL/SQL features, rather than additions introduced by that release. Building on the previous lesson's discount calculation, you will compare a function that returns a price with a procedure that supplies both the final price and the savings.
For the House-O-Pets application, calculating a quoted amount and recording a completed sale are different responsibilities. A price calculation naturally fits an expression. Recording a sale usually involves an operation with several steps. That distinction helps you design an interface before deciding which statements belong inside it.
| Attribute | Procedure | Function |
|---|---|---|
| Typical purpose | Perform an operation | Calculate or obtain a result |
| Function-style return value | None | Declares a return type and returns a value on normal completion |
| Parameters | May use IN, OUT and IN OUT | PL/SQL permits these modes; prefer IN parameters and the function result |
| Several results | Can expose several output parameters | One result may have a structured or collection type |
| Invocation | A PL/SQL statement, eligible SQL CALL, or client API | A PL/SQL expression, or a SQL expression when its requirements are met |
| Changing table data | Depends on execution context | Also context-dependent; SQL invocation adds restrictions |
| Organization | Nested, packaged or standalone | Nested, packaged or standalone |
A procedure is not inherently more capable than a function. Nor does a procedure have to change database tables. It might calculate several related outputs, validate an operation or coordinate calls to other routines. Conversely, a function can perform substantial work before producing its result.
The parameter list describes what crosses the routine's boundary. IN supplies an input and is the default mode. OUT supplies a result to the caller. IN OUT receives an initial value and can return an updated value. Use an appropriate caller variable for an output argument; a literal such as 85 cannot receive an assignment.
PL/SQL permits output parameters on functions, but Oracle recommends avoiding them. A function with a clear return value is easier to use in an expression without overlooking additional outputs. SQL-expression calls impose further requirements, discussed below. These distinctions follow Oracle's subprogram parameter documentation.
Names and units also matter. A parameter called p_rate needs a documented convention: does 15 mean 15 percent, or should the caller pass 0.15? An output called p_final_price tells the caller more than an output called p_result. Consistent naming reduces mistakes when several numeric values appear in one call.
In an ordinary function, RETURN NUMBER in the heading declares the result type. A statement such as RETURN l_total; supplies the value and ends that invocation. Every execution path that completes normally must return a value. An exception instead reports failure; it does not supply a successful result.
A procedure has no return-type clause. A bare RETURN; can exit it early, but RETURN l_total; is not a valid way to return a procedure result. Assign its output parameters instead. See Oracle's subprogram parts and RETURN statements.
“One function result” does not mean “one scalar field.” A PL/SQL function can return a record or collection type where that type is supported. The caller then receives one structured value. SQL use still depends on SQL type and invocation rules. See function declaration and definition.
Yes, a function called from PL/SQL can perform DML when its execution context permits it. The blanket statement that functions cannot insert, update or delete is incorrect. The important restrictions arise when a function executes within a SQL statement.
For ordinary SQL-invoked execution, a function called by a SELECT query cannot modify database data. A function called by DML also faces restrictions, including reading or changing the table modified by the invoking statement. Calling a procedure from inside the function does not remove those restrictions.
Functions invoked in SQL expressions need IN-only parameters and types supported in that SQL context. The database also restricts transaction control within SQL-invoked routines. Advanced autonomous-transaction cases are outside this lesson and should not be a routine workaround. Oracle documents the rules under functions invoked from SQL statements.
The following examples require no application tables. Use a learning schema with the CREATE PROCEDURE privilege, which covers creating these standalone PL/SQL routines. CREATE OR REPLACE replaces an existing routine with the same name, so check the names before running the script. These examples have been reviewed against the documentation; the displayed results are expected results, not an Oracle execution transcript.
Our teaching policy accepts a nonnegative price and a rate from 0 through 1. Neither input may be NULL. A rate of 0.15 means 15 percent, and the final price is rounded to two decimal places. A real application must choose its currency and rounding policy explicitly.
CREATE OR REPLACE FUNCTION price_after_discount (
p_price IN NUMBER,
p_rate IN NUMBER
) RETURN NUMBER
AS
BEGIN
IF p_price IS NULL OR p_price < 0 THEN
RAISE_APPLICATION_ERROR(
-20001, 'Price must be nonnegative and not NULL.');
END IF;
IF p_rate IS NULL OR p_rate < 0 OR p_rate > 1 THEN
RAISE_APPLICATION_ERROR(
-20002, 'Rate must be from 0 to 1 and not NULL.');
END IF;
RETURN ROUND(p_price * (1 - p_rate), 2);
END price_after_discount;
/
The function tests missing values explicitly. Comparisons alone do not reject NULL because a condition such as p_rate < 0 is not true when the rate is NULL. The calculation runs only after both inputs pass validation.
The RETURN expression calculates the price after the discount. The function neither changes a table nor prints its result. That keeps the caller free to use the number in an assignment, a larger calculation or an eligible SQL expression. The declaration follows Oracle's CREATE FUNCTION syntax.
After creating the function, request its result:
SELECT price_after_discount(100, 0.15) AS final_price
FROM dual;
The expected numeric value in FINAL_PRICE is 85. Your client's numeric formatting may show a different number of decimal places. The value comes from the function's return expression; the column alias simply gives that result a readable heading.
Suppose the caller needs both the final price and the savings. A procedure can provide two named outputs. Create this procedure after the function because it calls price_after_discount:
CREATE OR REPLACE PROCEDURE discount_breakdown (
p_price IN NUMBER,
p_rate IN NUMBER,
p_final_price OUT NUMBER,
p_savings OUT NUMBER
)
AS
BEGIN
p_final_price := price_after_discount(p_price, p_rate);
p_savings := ROUND(p_price - p_final_price, 2);
END discount_breakdown;
/
The first assignment obtains the function result. The second calculates the savings from the original price and that rounded result. There is one copy of the validation policy, inside the function, so both interfaces reject the same invalid inputs. The procedure performs no DML and requires no COMMIT to make these calculations available to its caller.
Here, the procedure's purpose is to make a pair of values available through a clear interface. It does not make the function obsolete. Callers that need only the final price can continue using the function directly. The routine declaration follows Oracle's CREATE PROCEDURE syntax.
The caller declares variables to receive the two outputs. Named argument notation makes the relationship between each formal parameter and the caller's variable visible:
SET SERVEROUTPUT ON
DECLARE
l_final_price NUMBER;
l_savings NUMBER;
BEGIN
discount_breakdown(
p_price => 100,
p_rate => 0.15,
p_final_price => l_final_price,
p_savings => l_savings
);
DBMS_OUTPUT.PUT_LINE('Final price: ' || l_final_price);
DBMS_OUTPUT.PUT_LINE('Savings: ' || l_savings);
END;
/
The expected displayed values are:
Final price: 85
Savings: 15
Read this sequence carefully. The procedure assigns l_final_price and l_savings through its output parameters. The caller then displays those variables. DBMS_OUTPUT is buffered diagnostic output that a client can retrieve; it is neither a function return value nor persistent application logging. See Oracle's DBMS_OUTPUT reference.
SET SERVEROUTPUT ON enables display in SQL*Plus or SQLcl. The slash on a separate line submits the preceding PL/SQL unit in that script environment. Other clients have their own script and output controls. A procedure is called as a statement, so do not put discount_breakdown in a SELECT expression.
SQL CALL is another invocation mechanism for eligible routines. SQL*Plus EXECUTE, often abbreviated to EXEC, is a client convenience command, not a PL/SQL keyword. The anonymous block above also gives you a place to declare receiving variables and process results. Oracle describes SQL invocation in its CALL reference.
| Price | Rate | Expected outcome |
|---|---|---|
| 100 | 0.15 | Final price 85; savings 15 |
| 100 | 0 | Final price 100; savings 0 |
| 100 | 1 | Final price 0; savings 100 |
| 0 | 0.15 | Final price 0; savings 0 |
| NULL or negative | Valid rate | Application error -20001 |
| Valid price | NULL, negative or greater than 1 | Application error -20002 |
RAISE_APPLICATION_ERROR uses application error numbers in the range -20000 through -20999. The procedure lets the function's error propagate rather than converting invalid input into an apparently successful NULL result. See raising exceptions explicitly.
If a call ends with an unhandled exception, do not rely on its output parameter values. Handle the failure before using results. This is particularly important when receiving variables already contain values from an earlier successful call. The caller must distinguish fresh successful outputs from failed execution.
Both kinds of subprogram can be nested inside another PL/SQL unit, placed in a package or created as standalone schema objects. A nested routine is useful for a helper needed only by its enclosing code. A package groups related operations behind a shared interface. The examples here are standalone routines so their declarations remain easy to compare.
A public packaged routine is declared in the package specification and implemented in the body. A standalone routine is created with its own SQL CREATE statement. These are organization choices, not differences that make one kind of subprogram universally preferable. Oracle explains them under nested, package and standalone subprograms.
When an application grows, consider grouping related pricing operations in a package. Keep their units, error meanings and output conventions consistent. A stable signature helps callers, but changing a routine's behavior can still affect them even when the parameter list stays the same.
An anonymous block is a submitted PL/SQL statement without a stored subprogram name. It can declare local items, execute statements and handle exceptions. A stored procedure is a named reusable subprogram. Both use PL/SQL block structure; “block” is not a synonym for “anonymous.” See Oracle's block reference.
| Feature | Anonymous block | Stored procedure |
|---|---|---|
| Identity | No stored subprogram name | Named standalone or packaged routine |
| Persistence | Submitted as source, not created as a named schema object | Stored until dropped or replaced |
| Reuse | The source can be submitted again | Callers invoke the stored routine |
| Inputs and outputs | Can reference client bind variables | Declares formal parameters |
| Role in this example | Calls the routine and displays results | Provides the reusable calculation interface |
The example combines both forms: the anonymous block acts as a caller, while the procedure holds reusable behavior. An application can also submit an anonymous block with bind variables to pass inputs and receive outputs. Repeated use does not require turning every caller block into another stored procedure.
Do not choose a procedure merely because someone describes it as “compiled once” or automatically faster. Stored units can be invalidated and require recompilation. Runtime performance also depends on the SQL, amount of work and call pattern. Oracle's ALTER PROCEDURE reference describes explicit and implicit recompilation.
Creating a routine defines database code; invoking it runs that code. The CREATE statements here are DDL. Oracle commits before a syntactically valid DDL statement and after successful DDL, so run setup separately from unfinished application transactions. See Oracle's COMMIT reference.
The example routines only calculate values. If a later procedure changes sales tables, decide which layer owns the transaction boundary. A reusable operation should have documented commit and rollback behavior so that callers can combine operations predictably. Calling a routine does not, by itself, mean every change it makes is committed.
For a known operation, accept business values such as a sale identifier or discount rate. Use fixed SQL with typed parameters rather than accepting an arbitrary WHERE clause. Binding one value does not secure a separately concatenated column name or condition.
If you have a few known query variants, explicit branches using IF and ELSIF can keep them readable. Genuinely dynamic identifiers need an application allowlist. Appropriate DBMS_ASSERT routines can assist validation, but do not sanitize arbitrary SQL predicates or replace authorization checks. See Oracle's SQL injection guidance.
For dynamic queries, fetching results is a separate responsibility: single-row retrieval uses EXECUTE IMMEDIATE ... INTO; multiple rows need bulk collection or a cursor opened with OPEN ... FOR. Bind values through the appropriate clauses. These mechanisms are covered in native dynamic SQL, rather than being necessary for the comparison in this lesson.
Ask what successful completion should give the caller. If the answer is a value that belongs in an expression, start with a function. If the answer is an operation with named outputs or several coordinated steps, consider a procedure. Then check the intended calling context, including whether SQL-expression use is required.
Before writing the body, name the inputs and outputs, specify valid ranges and decide how failure is reported. In the discount example, rejecting NULL explicitly and using the same validation for both interfaces makes their behavior predictable. Clear contracts matter more than counting how many statements a routine contains.
In the next lesson, you will apply these distinctions when creating a procedure that calculates a percentage and an average for a sales transaction.