| Lesson 3 | Syntax of a function |
| Objective | Identify the parts of a standalone Oracle function and distinguish valid syntax from common mistakes. |
A standalone stored function combines a heading with a PL/SQL body. The heading identifies the function, its inputs, and its return datatype. The body supplies the declarations and executable statements that implement the operation. Learning to recognize those boundaries makes a definition easier to write and helps you locate mistakes when Oracle reports compilation errors.
This lesson uses Oracle AI Database 26ai and ordinary scalar functions. The core structure is established PL/SQL syntax, not a new 26ai feature. The previous lesson discussed when functions are useful; here, the emphasis is on putting their parts in the correct order and checking a complete definition.
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN] datatype [DEFAULT expression], ...)]
RETURN return_datatype
[AUTHID {DEFINER | CURRENT_USER}]
{IS | AS}
-- Optional local declarations
BEGIN
-- Executable statements
RETURN result_expression;
[EXCEPTION
-- One or more complete exception handlers]
END [function_name];
/
Square brackets indicate optional material, braces group alternatives, and a vertical bar means choose one alternative. The ellipsis represents additional parameter declarations. Replace placeholders with real names, types, and statements; do not enter the notation itself. For example, choose IS or AS rather than typing both keywords.
The parameter list is optional as a whole. A function with no inputs omits that declaration list. Likewise, a function with no exception handlers omits the entire EXCEPTION section. The complete example below shows what remains after the schematic notation has been replaced.
CREATE FUNCTION defines a standalone schema function. Adding OR REPLACE permits an existing definition to be replaced, so use an available exercise name in your practice schema. Creating a function in your own schema requires the CREATE PROCEDURE system privilege. This privilege name applies to functions too.
The definition here is different from a local function declaration inside another PL/SQL block. A local declaration begins with FUNCTION and belongs to its containing scope; it is not independently created with CREATE FUNCTION. Packaged functions are organized within packages, which the course covers later.
Separate parameter declarations with commas. Each gives a formal parameter name and datatype; the name is what the function body uses. IN is the default mode, but writing it explicitly makes these examples easier to read. At a call site, the supplied values or expressions are the actual arguments.
An IN parameter can have a default introduced by DEFAULT or :=. The default is used when that argument is omitted. Passing NULL explicitly supplies a value and does not request the default. Place an optional trailing input after required inputs to make positional calls straightforward.
PL/SQL also permits OUT and IN OUT function parameters, although Oracle discourages them. This lesson uses input parameters and a return value; ordinary SQL-expression calls require IN parameters. Read Oracle's parameter documentation for other calling conventions.
RETURN NUMBER in the heading describes the datatype of the result. It does not calculate a number or finish the function. Do not put a semicolon immediately after this heading clause: the definition continues with optional clauses and IS or AS.
Use unconstrained declaration syntax, such as p_price IN NUMBER and RETURN NUMBER. Do not insert precision or length directly into these declarations as p_price IN NUMBER(10,2) or RETURN VARCHAR2(30). Local variable declarations have different rules and may include constraints. Named subtypes have additional rules that are unnecessary for this example.
IS and AS are alternatives for introducing this standalone implementation. Put any local variables between that keyword and BEGIN. Do not add DECLARE to introduce the function's own declaration section. If no local declarations are needed, BEGIN follows IS or AS directly.
BEGIN starts the executable section. Assignment, conditional logic, SQL operations, and calls to other subprograms belong in this section when their context permits them. Each statement needs its appropriate terminator. A variable assignment uses :=, whereas an equality comparison uses =.
A separate nested DECLARE ... BEGIN ... END; block can legally appear within the executable section. It introduces another scope. That is different from putting DECLARE between the function's IS and its main BEGIN. Start with a single body before adding nested blocks.
The heading's RETURN clause declares a type; a statement such as RETURN l_total; supplies the result and immediately returns control to the caller. A function may contain several RETURN statements for different branches. Each normally completing path must return an appropriate value, but a path that propagates an exception does not complete normally.
The expression can be a variable, literal, or calculation compatible with the declared return type. NULL can also be an intentional result. A bare RETURN; is not the correct return statement for the ordinary scalar functions in this lesson. See Oracle's RETURN reference for other contexts.
END closes the body, and optionally repeating the function name makes the boundary clearer. The closing statement ends with a semicolon. In SQL*Plus and SQLcl scripts, the slash on a separate line submits the buffered definition. That slash is a client command, not part of PL/SQL grammar. Other clients may require a script execution mode.
The following example multiplies a supplied price by a quantity. It requires no sample tables, sequences, or course downloads. The parameter called quantity is simply an input; this example does not add a QUANTITY column to the five-table Pet Store project.
CREATE OR REPLACE FUNCTION lesson3_calculate_total (
p_price IN NUMBER,
p_quantity IN NUMBER DEFAULT 1
) RETURN NUMBER
AUTHID CURRENT_USER
IS
l_total NUMBER;
BEGIN
l_total := p_price * p_quantity;
RETURN l_total;
END lesson3_calculate_total;
/
SHOW ERRORS FUNCTION lesson3_calculate_total
Read it in three passes. First, examine the interface: two numeric inputs and a numeric result. Second, find the local declaration, l_total NUMBER;. Third, trace the executable body: multiply the inputs, assign the product to the local variable, and return it.
AUTHID CURRENT_USER selects invoker's rights. Omitting AUTHID from a standalone function selects definer's rights by default. This example accesses no tables, so it keeps attention on the calculation; the rights clause does not grant privileges or replace access checks.
The function deliberately implements multiplication rather than a complete billing policy. A zero operand produces zero, a NULL operand produces NULL, and negative or fractional inputs are not rejected. It performs no currency rounding. Those choices are part of its simple contract, not recommendations for every application.
Submitting a CREATE statement is not the same as confirming an error-free compilation. In SQL*Plus or SQLcl, SHOW ERRORS names the object whose diagnostics you want to inspect. Keep it outside the function body.
A client without that command can query USER_ERRORS, which describes diagnostics for stored objects owned by the current user:
SELECT line, position, text
FROM user_errors
WHERE name = 'LESSON3_CALCULATE_TOTAL'
AND type = 'FUNCTION'
ORDER BY sequence;
The object name is uppercase because the example uses an ordinary unquoted identifier. LINE and POSITION help locate a diagnostic, TEXT contains its message, and SEQUENCE supplies the intended ordering. If the query returns nothing, that alone does not prove the function exists in the intended schema; check that the creation step succeeded and that you are connected as the expected user.
SELECT lesson3_calculate_total(12.50, 3) AS total
FROM dual;
SELECT lesson3_calculate_total(12.50) AS total
FROM dual;
SELECT lesson3_calculate_total(12.50, NULL) AS total
FROM dual;
The expected numerical results are 37.5 and 12.5, followed by NULL. The second call omits quantity and uses its default of 1. The third supplies NULL explicitly, so the multiplication produces NULL instead. A client might display trailing zeroes or show a null result as an empty cell.
SET SERVEROUTPUT ON
DECLARE
l_total NUMBER;
BEGIN
l_total := lesson3_calculate_total(12.50, 3);
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/
This caller is an anonymous block, so DECLARE introduces its local variable. The function invocation is an expression on the right side of the assignment. The block then sends the result to DBMS_OUTPUT. SET SERVEROUTPUT enables its display in supporting clients; it is not a statement inside the function.
The examples describe expected behavior, not a transcript of an Oracle run. In your practice database, verify compilation and compare the observed results with the stated contract. Checking a successful call, an omitted argument, an explicit NULL, and zero is more informative than checking only one positive calculation.
The complete example has no EXCEPTION section. Unexpected errors therefore propagate to the caller. Do not automatically catch VALUE_ERROR and return NULL: a conversion or arithmetic failure is different from a calculation whose input is intentionally NULL.
When a function needs a handler, put EXCEPTION after the executable statements and before the final END. Each handler needs a WHEN clause and executable statements. A comment saying “handle the error” is not a complete handler.
For a handler that cannot resolve a failure, re-raising preserves it for the caller. An OTHERS handler, if present, comes last. Adding a handler that only re-raises is unnecessary in the simple example; the useful lesson is to avoid silently turning unexpected failures into ordinary results. Oracle's exception-handler reference describes the syntax and recommendations.
The entries below are fragments for comparison, not complete programs to execute.
| Mistake or assumption | Correction |
|---|---|
| DECLARE immediately after the function's IS | Put local declarations directly after IS or AS. |
p_price IN NUMBER(10,2) | Use p_price IN NUMBER; handle business constraints deliberately. |
RETURN NUMBER; in the heading | Continue the heading and body definition without that semicolon. |
RETURN; in an ordinary scalar function | Provide the return expression. |
| Expecting a default to replace an explicit NULL | Omit the argument to use its default, or implement a separate NULL policy. |
| A normal branch reaches END without returning | Ensure that branch returns an appropriate value. |
| Typing brackets and placeholders from the outline | Use the complete example as the guide to executable syntax. |
When a compiler message points near BEGIN or END, inspect the preceding lines too. A missing separator or an unfinished declaration can make the parser report the problem at the next keyword. Correct one clear defect, resubmit the definition, and inspect the new diagnostics before making unrelated changes.
A function can compile successfully but fail when invoked from a particular SQL context. For ordinary SQL-expression calls, use IN parameters and SQL-compatible argument and result types. Oracle 26ai supports SQL BOOLEAN, so the old blanket statement that Boolean functions cannot be called from SQL is no longer appropriate.
For the ordinary non-autonomous functions used here, a SELECT-invoked function must not modify database tables. SQL-invoked functions also face restrictions on transaction control and DDL, including actions performed through called subprograms. These are calling-context rules, not a universal prohibition on DML in every PL/SQL function.
The arithmetic example avoids those issues by reading only its inputs and returning a calculation. Consult Oracle's SQL invocation rules when adding database operations, and its 26ai release notes for SQL BOOLEAN support.
Keep the numeric examples numeric. If another function needs to handle large text or binary values, consider CLOB or BLOB rather than LONG or LONG RAW. Oracle documents the historical deprecation of the LONG family in Oracle8i 8.1.6 and its continued backward-compatibility role; these types were not simply removed in 26ai.
This is datatype-selection guidance, not a request to migrate the course tables or introduce object types. The datatype reference explains the restrictions in detail.
Oracle also documents the following session settings. They are reference syntax, not required setup commands for this lesson:
ALTER SESSION DISABLE COMMIT IN PROCEDURE;
ALTER SESSION ENABLE COMMIT IN PROCEDURE;
DISABLE prevents called PL/SQL procedures and stored functions from issuing COMMIT or ROLLBACK in that session. ENABLE allows them again where the calling context permits. These settings are separate from CREATE FUNCTION and do not override the restrictions on SQL-invoked functions. Transaction design belongs to the later transaction-control module. See the ALTER SESSION reference.
Before moving on, locate the function name, parameter declarations, RETURN datatype, IS or AS, local declarations, BEGIN, return statement, and END in the complete example. Then identify which commands belong to the client rather than the function. Being able to explain those boundaries is the objective of this lesson.
Continue to creating a function that returns a value. For the complete standalone definition grammar, consult Oracle's CREATE FUNCTION reference.