PL SQL Functions: How to Create, Call, and Test Them

PL SQL functions let you define a calculation or lookup once and reuse it wherever you need its result. In Oracle, a PL/SQL function is a named program unit that accepts zero or more parameters and returns a value. This guide shows how to write a CREATE FUNCTION statement, call the function from SQL and PL/SQL, and decide what should happen when an input is missing or a lookup finds no match.

What are PL SQL functions used for?

A function is a good fit when the caller needs an answer: an annual salary, a formatted label, or a rate associated with a code. A procedure is usually a better fit when the main purpose is to perform an action, such as posting an invoice or updating several tables. The key question is whether the caller needs to use a value or request an operation.

Oracle already provides SQL functions such as ROUND, UPPER, and COALESCE. Use those directly when they express the rule clearly. A custom PL/SQL function becomes useful when the rule combines several operations, needs a descriptive name, or must behave consistently across multiple callers.

The examples below create standalone functions, which are stored in your schema. PL/SQL also supports functions inside packages and local functions inside PL/SQL blocks. A standalone function is a convenient starting point because you can create and test it independently.

How to create a function in Oracle PL/SQL

A function definition has a header and a body. The header names the function, lists its parameters, and declares its return type. The body contains the statements that calculate and return the result. Here is a minimal function that doubles a number:

CREATE OR REPLACE FUNCTION double_amount (p_amount IN NUMBER)
RETURN NUMBER
IS
BEGIN
  RETURN p_amount * 2;
END double_amount;
  • CREATE OR REPLACE FUNCTION creates the function or replaces an existing definition of the same name in the schema.
  • p_amount IN NUMBER declares a numeric input. IN is the default mode, but writing it explicitly makes the interface easier to read.
  • RETURN NUMBER declares the type of the result. The RETURN statement inside the body supplies the actual value.
  • IS introduces the body. Declare any local variables between IS and BEGIN, and put executable statements after BEGIN.

Every normal execution path must reach a RETURN statement. If a path reaches the end of the function without returning a value, Oracle raises an error at runtime. A path that deliberately raises an exception does not need a return value.

When running these definitions as a script in SQL*Plus, SQLcl, or SQL Developer’s Run Script mode, put a slash on a line by itself after each function definition or anonymous PL/SQL block. The slash is a client command that submits the buffered unit; it is not part of PL/SQL. If you send a definition through an application driver, do not append the slash to the statement.

Example 1: Calculate an annual salary

Suppose a report needs to convert a monthly salary into a total for a specified number of paid months. The default is 12 months, but callers can supply another value. This example treats a missing monthly salary as unknown, returns NULL for it, and rejects a supplied month count that is null, nonpositive, or fractional.

CREATE OR REPLACE FUNCTION annual_salary (
  p_monthly_salary IN NUMBER,
  p_paid_months IN NUMBER DEFAULT 12
) RETURN NUMBER
IS
BEGIN
  IF p_paid_months IS NULL OR p_paid_months <= 0
     OR p_paid_months <> TRUNC(p_paid_months) THEN
    RAISE_APPLICATION_ERROR(-20001, 'Paid months must be a positive whole number.');
  END IF;
  IF p_monthly_salary IS NULL THEN
    RETURN NULL;
  END IF;
  RETURN ROUND(p_monthly_salary * p_paid_months, 2);
END annual_salary;

The function validates the month count first, so an invalid count raises an error even if the salary is also missing. The default applies only when the caller omits the argument. Passing NULL explicitly does not trigger the default. This distinction matters when an argument comes from a nullable table column or an optional form field.

Call a PL/SQL function from a SQL query

Use the function as an expression in the SELECT list. Oracle’s DUAL table makes it easy to test a function without creating a table of your own:

SELECT annual_salary(3500) AS standard_total,
       annual_salary(3500, 10) AS ten_month_total
FROM dual;

The first result is 42000; the second is 35000. If you later call the function with a column instead of a literal, each call uses the supplied row’s value. For a simple calculation used in just one query, an inline SQL expression may be clearer. Use the stored function when giving the rule a name and sharing it across callers is worth the extra dependency.

Call the same function from a PL/SQL block

Inside PL/SQL, assign the return value directly to a variable. You do not need to run a SELECT against DUAL. This example uses named notation so the two arguments are easy to distinguish:

DECLARE
  l_total NUMBER;
BEGIN
  l_total := annual_salary(p_monthly_salary => 3500, p_paid_months => 10);
  DBMS_OUTPUT.PUT_LINE(l_total);
END;

The block writes 35000 to the DBMS_OUTPUT buffer. Enable DBMS Output in your client to see it. In SQL*Plus or SQLcl, run SET SERVEROUTPUT ON before the block. Named notation also makes parameter names part of the interface: renaming a parameter can break callers that refer to it by name.

Example 2: Look up a shipping fee in a table

A function can also return a value stored in a table. This example looks up the fee for a shipping zone. Run the setup in a schema where you can create tables and functions, then test it in the same session so the sample rows are visible:

CREATE TABLE demo_shipping_rates (
  zone_code VARCHAR2(10) PRIMARY KEY,
  fee NUMBER(8, 2) NOT NULL
);
INSERT INTO demo_shipping_rates (zone_code, fee) VALUES ('LOCAL', 4.95);
INSERT INTO demo_shipping_rates (zone_code, fee) VALUES ('PICKUP', 0);

The primary key guarantees at most one row for a zone. The NOT NULL constraint on the fee lets the function use NULL to indicate that no rate was found, without confusing a missing rate with a valid zero charge.

CREATE OR REPLACE FUNCTION shipping_fee (p_zone_code IN VARCHAR2)
RETURN NUMBER
IS
  l_fee demo_shipping_rates.fee%TYPE;
BEGIN
  SELECT fee
  INTO l_fee
  FROM demo_shipping_rates
  WHERE zone_code = UPPER(TRIM(p_zone_code));
  RETURN l_fee;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    RETURN NULL;
END shipping_fee;

The %TYPE declaration gives the local variable the column’s data type. UPPER and TRIM let a caller pass an input such as ‘ local ‘ because the stored codes in this example are uppercase and have no surrounding spaces. SELECT INTO expects exactly one row: it raises NO_DATA_FOUND when there is no match and TOO_MANY_ROWS if there is more than one. Here the primary key prevents multiple matches, so the function handles only the expected missing-row case.

SELECT shipping_fee(' local ') AS local_fee,
       shipping_fee('PICKUP') AS pickup_fee,
       shipping_fee('UNKNOWN') AS unknown_fee
FROM dual;

The results are 4.95, 0, and NULL, respectively. Returning zero for an unknown zone would make it look as though shipping were free. If an unknown zone must stop checkout instead, raise an application error in the NO_DATA_FOUND handler. Either choice can be correct; what matters is that callers know the difference between a missing rate and a legitimate zero.

How to test and debug PL SQL functions

Check compilation errors before testing behavior

Oracle can create a function object with compilation errors. If your client reports that the function was created with errors, use SHOW ERRORS FUNCTION annual_salary in a client that supports the command, or query USER_ERRORS directly:

SELECT line, position, text
FROM user_errors
WHERE name = 'ANNUAL_SALARY' AND type = 'FUNCTION'
ORDER BY sequence;

Start with the first error. A missing semicolon or an unclosed IF block can cause more messages later in the definition. For a function that queries a table, also verify that the table and columns exist and that the function owner has the necessary privileges. For an ordinary definer-rights function that accesses another schema’s table, a grant through a role alone is not enough.

Test the return value and the failure paths

A function that compiles may still implement the wrong rule. Test defaults, boundary values, and missing data separately. Run any call expected to raise an error on its own so it does not prevent you from seeing other results.

  • Default argument: annual_salary(3500) should return 42000.
  • Explicit argument: annual_salary(3500, 1) should return 3500.
  • Missing salary: annual_salary(NULL) should return NULL, not zero.
  • Invalid month count: annual_salary(3500, 0), annual_salary(3500, 2.5), and annual_salary(3500, NULL) should each raise ORA-20001.
  • Lookup behavior: test a known zone, an unknown zone, and the valid zero-fee pickup option.

When to use a function, a join, or a procedure

Use a function in a SQL query when it represents a reusable expression and its parameter and return types work in SQL. The examples use NUMBER and VARCHAR2 and do not change data. Avoid building an ordinary SELECT around a function that inserts, updates, or deletes rows: Oracle generally prohibits those changes in functions invoked from a query. If the purpose is to change data, make the action explicit in a procedure and decide where the transaction should be managed.

For a lookup across many rows, consider a join rather than calling a PL/SQL function for each row. If a report already contains a zone code for every shipment, joining directly to the rates table lets Oracle optimize the lookup as part of the query. Use a left join if unmatched shipments should remain in the report with a NULL fee. A lookup function is often simpler for a caller that needs just one rate, but it is not automatically the best choice for a large report.

Before creating a function, write down what it promises: the inputs it accepts, the value it returns, and what it does when it cannot produce that value. Use a custom function when that contract captures a rule worth reusing. Otherwise, a built-in function, an inline expression, or a join may do the job with less code.