Sub topic 2
Procedures and functions: what they are and when to use each
This chapter assumes you can write SQL DML and an anonymous PL/SQL block with DECLARE, BEGIN, EXCEPTION, and END. It also assumes you know the basic Oracle data types and have a schema with the CREATE PROCEDURE privilege. Later chapters cover the full CREATE syntax, parameter modes, and exceptions. Here you learn how the two kinds of subprogram differ and how to choose between them.
Stored subprograms versus anonymous blocks
An anonymous block has no name. The client sends its text to the database, which compiles and runs it, then discards it. A stored subprogram is a named block that Oracle compiles once and keeps in the data dictionary. You can call it again from any session that has permission.
Storing a block gives you these benefits:
- Reuse. One definition serves every application and script.
- Access control. You grant
EXECUTEon the subprogram instead of granting table privileges. - Fewer round trips. The client makes one call and the logic runs next to the data.
- Dependency tracking. Oracle records which tables and subprograms each one uses.
Oracle has two kinds of stored subprogram: procedures and functions. Both share the same block structure (declarations, executable section, exception section). They differ in what they return and where you can call them.
The core difference
A procedure performs an action. It is called as a complete statement and returns no value through its name. It can still send data back to the caller through OUT and IN OUT parameters.
A function computes a value. It must return exactly one value of a declared type with RETURN. The call is an expression, so it can appear wherever a value of that type is allowed.
| Aspect | Procedure | Function |
|---|---|---|
| Purpose | Do something | Compute something |
| Return value | None through its name | Exactly one, declared with `RETURN type` |
| How it is called | As a statement | Inside an expression |
| Callable from SQL | No | Yes, if it meets the SQL restrictions |
| Typical use | DML, workflows, multiple results | Calculations, lookups, formatting |
| `RETURN` statement | Optional, with no value, to exit early | Required, with a value, on every path |
The same task written both ways
The first example is a procedure. It does work and reports nothing through its name.
CREATE OR REPLACE PROCEDURE give_bonus (
p_employee_id IN employees.employee_id%TYPE,
p_amount IN NUMBER
) AS
BEGIN
UPDATE employees
SET salary = salary + p_amount
WHERE employee_id = p_employee_id;
END give_bonus;
/The second example is a function. It calculates a value and changes nothing.
CREATE OR REPLACE FUNCTION bonus_for (
p_salary IN employees.salary%TYPE,
p_percent IN NUMBER
) RETURN NUMBER AS
BEGIN
RETURN ROUND(p_salary * p_percent / 100, 2);
END bonus_for;
/The call sites show the other difference. The procedure is a statement. The function is part of an expression.
DECLARE
v_bonus NUMBER;
BEGIN
v_bonus := bonus_for(5000, 8); -- function inside an assignment
give_bonus(100, v_bonus); -- procedure as a statement
DBMS_OUTPUT.PUT_LINE('Bonus: ' || bonus_for(5000, 8));
END;
/Calling a function as a bare statement, such as bonus_for(5000, 8);, fails to compile with PLS-00221. Oracle reports that the name is not a procedure. Using a procedure inside an expression also fails to compile.
A decision flow
These rules cover most decisions:
- If the main point is an effect (an insert, an update, sending a message, a multi-step process), write a procedure.
- If the main point is a result (a calculation, a lookup, a conversion), write a function.
- If you need several results at once, use a procedure with
OUTparameters. A function can return only one value throughRETURN. - If you want to use the logic in a
SELECT,WHERE, orORDER BY, it has to be a function.
Reading what is stored
Oracle lists your standalone subprograms in USER_OBJECTS. The STATUS column shows whether each one is currently valid.
SELECT object_name, object_type, status
FROM user_objects
WHERE object_type IN ('PROCEDURE', 'FUNCTION')
ORDER BY object_type, object_name;The source text is in USER_SOURCE. Filter on NAME and TYPE, and order by LINE.
Edge cases and gotchas
A function must return on every path
Oracle checks that a function contains a RETURN statement, but it does not prove that every path reaches one. If execution leaves the body without returning, the call fails at run time with ORA-06503: PL/SQL: Function returned without value. Branches such as IF without an ELSE are the usual cause. Handle NO_DATA_FOUND explicitly too, as in the get_full_name example from the Topic Spine. That function returns NULL when no row matches.
Side effects in functions called from SQL
PL/SQL lets a function change data when you call it from a PL/SQL block. SQL does not. If a function that performs DML is called from a SELECT, Oracle rejects it at run time.
CREATE OR REPLACE FUNCTION touch_employee (
p_employee_id IN employees.employee_id%TYPE
) RETURN NUMBER AS
BEGIN
UPDATE employees
SET salary = salary
WHERE employee_id = p_employee_id;
RETURN p_employee_id;
END touch_employee;
/
SELECT touch_employee(100) FROM dual;
-- ORA-14551: cannot perform a DML operation inside a queryThe function compiles and works fine when called from a block. It fails only when SQL calls it. That is why a function meant for SQL should only read data and compute values. The chapter on calling functions from SQL lists the full set of restrictions.
Functions with OUT parameters
The language allows a function to declare OUT or IN OUT parameters in addition to its return value. It is legal, but such a function cannot be called from SQL. It also hides outputs in the parameter list, so the caller cannot see from the call that variables are being changed. If you need several outputs, use a procedure.
Types that SQL cannot see
A function called from SQL can only use types that SQL understands. Before Oracle Database 23ai, BOOLEAN and PL/SQL-only record types were not available in SQL. A function that returns BOOLEAN works only from PL/SQL. If you want a yes/no answer in a query, return 'Y'/'N' or 1/0 instead.
Transaction control
Procedures often need to coordinate a unit of work, and by default a subprogram runs inside the caller's transaction. A COMMIT or ROLLBACK inside a procedure ends the caller's transaction as well. It is usually better to leave transaction control to the outermost caller. Reserve commits inside subprograms for cases where the procedure is meant to be the entry point of a whole job. A function called from SQL must not commit at all.
Early exit in a procedure
A procedure can use RETURN with no value to stop early. This is useful for guard checks at the top.
CREATE OR REPLACE PROCEDURE archive_employee (
p_employee_id IN employees.employee_id%TYPE
) AS
BEGIN
IF p_employee_id IS NULL THEN
RETURN; -- nothing to do, exit without error
END IF;
DELETE FROM employees
WHERE employee_id = p_employee_id;
END archive_employee;
/Using RETURN with a value inside a procedure is a compile error.
Where subprograms live
Everything above uses standalone subprograms, created directly in a schema with CREATE PROCEDURE or CREATE FUNCTION. Two other places exist:
- Packaged subprograms are defined in a package, which groups related procedures and functions. A later chapter covers packages and overloading.
- Local subprograms are declared in the
DECLAREsection of another block. They exist only while that block runs and are not stored by name in the schema.
The procedure-versus-function rules apply equally to all three.
Summary
- A procedure is called as a statement and performs an action. A function is called inside an expression and returns exactly one value.
- Use a procedure for effects and for multiple outputs. Use a function for computations and lookups, and for anything SQL must call.
- Keep SQL-callable functions free of DML and transaction control.
- Make every function path end in
RETURN, or the call fails withORA-06503.
Exercise
A teammate writes a function next_invoice_no that inserts a row into a sequence-tracking table and returns the new number. It works in an anonymous block, but SELECT next_invoice_no FROM dual fails with ORA-14551. Explain why, and name one way to restructure the code.
Show answer
SQL does not allow a function called from a query to perform DML, so the insert inside the function raises ORA-14551 when it runs from a SELECT. It works from a block because PL/SQL permits DML in functions. One fix is to turn the logic into a procedure with an OUT parameter (for example get_next_invoice_no(p_no OUT NUMBER)) and call it from a block. Another is to use an Oracle sequence, which a query can read with NEXTVAL, and keep any tracking insert in a separate procedure.
Exercise
You need a routine that, given a job ID, returns both the lowest and highest salary for that job. Should it be a procedure or a function? Justify your choice.
Show answer
A procedure with two OUT parameters. A function's RETURN carries only one value, and a function with OUT parameters could not be called from SQL anyway. This matches the get_salary_range example in the Topic Spine.