Sub topic 9
Calling stored functions from SQL and the restrictions that apply
This chapter assumes you can write a basic stored function, know what IN parameters are, and can run SELECT, INSERT, UPDATE and DELETE statements. You will see how to call a stored function inside a SQL statement, what the database forbids in such a function, and how the call affects performance.
Where a function can appear in SQL
A stored function is an expression that returns one value. Anywhere SQL accepts an expression of that type, you can call the function. Common places are:
- The select list of a query.
- The WHERE, GROUP BY, HAVING and ORDER BY clauses.
- The VALUES clause of an INSERT.
- The SET clause of an UPDATE.
- A virtual column definition or a function-based index.
The function get_full_name from the earlier chapters returns the employee's name as a string. This query calls it from the select list.
SELECT employee_id, get_full_name(employee_id) AS full_name
FROM employees
WHERE department_id = 60;Oracle runs the function once for each row that the query returns. If the function runs a query of its own, that query runs once per row too. The idea is easy to use, but it is a common source of slow SQL.
UPDATE employees
SET email = UPPER(SUBSTR(get_full_name(employee_id), 1, 8))
WHERE department_id = 60;You can also use the function in a WHERE clause. Be careful here. The function runs for every row that the other predicates do not filter out first, and the optimizer cannot use a normal index on the function's result.
SELECT employee_id
FROM employees
WHERE get_full_name(employee_id) = 'Alexander Hunold';Execution flow
The SQL engine and the PL/SQL engine are separate. Each call from SQL into PL/SQL switches from one engine to the other, and this has a cost. This is called a context switch.
For a few hundred rows, you will not notice the cost. For millions of rows, the switches and the extra queries add up. When a function only joins or formats columns, a plain SQL expression or join is often faster than a function.
Restrictions on functions called from SQL
Oracle limits what a function can do when SQL calls it. The purpose is to keep a query predictable. A query that changes data while it reads data can produce results that depend on the order of rows.
A function called from a query must follow these rules:
- It must be a stored function or a function in a package. It cannot be a function declared only inside an anonymous block.
- All its parameters must be IN parameters. OUT and IN OUT parameters are not allowed.
- The parameter types and the return type must be SQL types such as NUMBER, VARCHAR2 and DATE. Types that exist only in PL/SQL, such as BOOLEAN, PLS_INTEGER (in older releases), records and associative arrays, do not work.
- It cannot end the transaction. COMMIT, ROLLBACK, SAVEPOINT and ALTER SESSION are not allowed.
- It cannot run DML (INSERT, UPDATE, DELETE) when SQL calls it from a SELECT statement.
- When SQL calls it from INSERT, UPDATE or DELETE, it cannot read or change the table that the statement is changing.
Rules 5 and 6 are the ones that surprise people. Here is a function that tries to write a row.
CREATE OR REPLACE FUNCTION log_and_name (
p_employee_id IN employees.employee_id%TYPE
) RETURN VARCHAR2 AS
BEGIN
INSERT INTO audit_log (employee_id, logged_at)
VALUES (p_employee_id, SYSDATE);
RETURN get_full_name(p_employee_id);
END log_and_name;
/
SELECT log_and_name(employee_id) FROM employees;The function compiles without errors, because the restriction is checked at run time. The SELECT then fails with this error.
ORA-14551: cannot perform a DML operation inside a queryRule 6 produces a different error. Suppose a function reads employees and you call it in an UPDATE of employees.
UPDATE employees
SET salary = get_dept_max_salary(department_id) * 0.9;If get_dept_max_salary selects from employees, Oracle can raise ORA-04091: table is mutating, trigger/function may not see it. The same error is well known from row triggers. It means the function tried to see a table that is half way through a change.
Purity and the privileges the function needs
Oracle used to describe these rules with the pragma RESTRICT_REFERENCES, which declared a function as not writing to the database (WNDS), not reading it (RNDS), and so on. Current releases check the rules at run time, so you do not need the pragma in new code. You might still see it in older packages.
A function does not need to be purely mathematical. It can read tables, and many useful functions do. The restrictions concern writes and transaction control. They do not prevent reads.
Controlling the cost of calling a function
There are four main ways to reduce the cost of a function in SQL.
| Technique | What it does | When to use it |
|---|---|---|
| Rewrite as SQL | Replaces the function with a join or expression | The function only combines columns or looks up a value |
| DETERMINISTIC | Tells Oracle that the same input always gives the same output | The function uses only its parameters and no session state or tables |
| RESULT_CACHE | Stores results in a shared cache, invalidated when dependent tables change | The function reads data that changes rarely |
| Scalar subquery caching | Wraps the call as `(SELECT f(x) FROM dual)` | The same input values repeat in one query |
The scalar subquery form asks Oracle to cache the result for each distinct input during the statement. It is an old and effective trick.
SELECT employee_id,
(SELECT get_full_name(e.employee_id) FROM dual) AS full_name
FROM employees e
WHERE department_id = 60;The advantage appears when an input value occurs many times. If you call get_dept_name(department_id) over 100,000 rows from 20 departments, the cached form calls the function about 20 times.
A function-based index is a different use of DETERMINISTIC. Oracle accepts only deterministic functions in an index expression, because it must be able to compute the same value later when it looks up the row.
CREATE OR REPLACE FUNCTION normalize_name (
p_name IN VARCHAR2
) RETURN VARCHAR2
DETERMINISTIC
IS
BEGIN
RETURN UPPER(TRIM(p_name));
END normalize_name;
/
CREATE INDEX emp_last_name_norm_ix
ON employees (normalize_name(last_name));After this, a predicate such as WHERE normalize_name(last_name) = 'KING' can use the index. If you later change the function body, the index entries become wrong, because Oracle does not recompute them. Rebuild the index after you change such a function.
Names, schemas and the SQL-visible signature
A function in SQL follows the usual name resolution rules. If the function is in another schema, grant EXECUTE on it and call it with the schema prefix, or create a synonym. A package function is called as package_name.function_name.
SELECT fmt.to_label(salary) AS salary_label
FROM employees
WHERE department_id = 60;In SQL you can use positional notation for arguments. In older releases, named notation (p_value => salary) in SQL was not allowed. Oracle 11g and later accept it. If your database is older than that, use positional calls.
A parameter with a default value can be left out, but only in the trailing positions when you use positional notation. The rules are the same as in PL/SQL blocks.
Common errors
| Error | Likely cause | Fix |
|---|---|---|
| ORA-14551 | The function runs DML and SQL called it from a query | Move the DML out, or call the function from a block |
| ORA-04091 | The function reads the table being modified by the calling DML | Compute the value in the SQL statement, or in a separate step |
| ORA-06575 | The function is invalid, or a package function does not meet the purity rules | Recompile and read `USER_ERRORS` |
| ORA-00904 | The function name is misspelled, or you lack EXECUTE privilege | Check the name and the grants |
| PLS-00231 | The function cannot be used in SQL, often because of a parameter or return type | Use SQL types and IN parameters only |
Exercise
The function next_invoice_no reads the maximum invoice number, adds 1, writes a row to a counter table, and returns the new number. It works when you call it from an anonymous block. What happens when you call it with SELECT next_invoice_no FROM dual, and how would you redesign it so that a query can use it?
Show answer
The SELECT fails at run time with ORA-14551, because the function runs DML inside a query. To redesign it, use a sequence, which is meant for this purpose: SELECT invoice_seq.NEXTVAL FROM dual, or insert with invoice_seq.NEXTVAL in the VALUES clause. If you need a counter table, keep the function with DML as a procedure with an OUT parameter and call it from a PL/SQL block, not from a query.
Exercise
A query calls get_dept_name(department_id) for 200,000 employee rows in 27 departments. Name two changes that reduce the number of times the function body runs or the number of context switches.
Show answer
Wrap the call in a scalar subquery, (SELECT get_dept_name(e.department_id) FROM dual), so that Oracle caches the result for each distinct department. Alternatively, replace the function with a join to the departments table, which removes the context switches entirely. Declaring the function RESULT_CACHE also helps, if the department data changes rarely.