Sub topic 8
Functions that change data
This chapter covers SQL functions that run INSERT, UPDATE or DELETE. It assumes you can write a basic CREATE FUNCTION ... LANGUAGE sql and know what a return type is. It also assumes you know what VOLATILE, STABLE and IMMUTABLE mean. You should be comfortable with RETURNING on plain DML statements.
Why a function should change data
A function that modifies data gives callers one named operation instead of raw SQL. The application calls create_customer('Ada', '[email protected]') and does not need to know which table or columns are involved. The function can also hand back the generated key, so the caller needs no second query.
Data-modifying SQL functions are plain SQL statements inside a function body. They have no loops, variables or exception blocks. For that reason they are short and easy to reason about.
The last statement rule
A SQL function body can hold several statements, separated by semicolons. PostgreSQL runs them in order. The function's result comes from the last statement only.
The last statement must produce a result that matches the declared return type:
- If the function returns a scalar type, the last statement must be a
SELECT, or a DML statement withRETURNING, that yields one column. - If the function returns
void, the last statement can be anything, and its output is discarded. - If the function returns a set or a table, the last statement can produce many rows.
An INSERT, UPDATE or DELETE yields rows only when it has a RETURNING clause. RETURNING therefore matters here. Without it, a function declared to return a value fails when it is created or called, because the last statement has no output to return.
INSERT ... RETURNING as the result
This example returns the new row's id:
-- Assumes a table customers(id serial primary key, name text, email text)
CREATE FUNCTION create_customer(p_name text, p_email text)
RETURNS int
LANGUAGE sql
AS $$
INSERT INTO customers (name, email)
VALUES (p_name, p_email)
RETURNING id;
$$;
SELECT create_customer('Ada', '[email protected]');The INSERT is the last and only statement. RETURNING id produces one int column, which matches RETURNS int. The call returns the id that the serial column generated.
Two details are worth knowing:
- The function has no volatility keyword, so it defaults to
VOLATILE. That is correct for a function that writes data. - If the
INSERTproduced more than one row, a scalar function would return only the first row and discard the rest. A single-rowVALUESlist produces one row, so that is not a problem here.
Returning more than the key
RETURNING can list several columns or use *. To return them, declare a composite return type. A table's name works as a type, and RETURNS TABLE works as well.
-- Assumes a table customers(id serial primary key, name text, email text)
CREATE FUNCTION rename_customer(p_id int, p_name text)
RETURNS TABLE (id int, name text, email text)
LANGUAGE sql
AS $$
UPDATE customers AS c
SET name = p_name
WHERE c.id = p_id
RETURNING c.id, c.name, c.email;
$$;
SELECT * FROM rename_customer(1, 'Ada Lovelace');If no row matches p_id, the function returns zero rows, not an error. Callers should be ready for an empty result. A scalar-returning version of the same function would return NULL in that case.
The RETURNS TABLE column names (id, name, email) are also visible inside the body as output parameters. They can clash with column names in your statements. The example qualifies every column with the alias c, so c.id is never confused with the output parameter id. Build the habit of qualifying column references in data-modifying functions.
Several statements in one function
A function body can run a write and then read the result:
-- Assumes tables accounts(id int primary key, balance numeric)
CREATE FUNCTION transfer_and_report(p_from int, p_to int, p_amount numeric)
RETURNS numeric
LANGUAGE sql
AS $$
UPDATE accounts SET balance = balance - p_amount WHERE id = p_from;
UPDATE accounts SET balance = balance + p_amount WHERE id = p_to;
SELECT balance FROM accounts WHERE id = p_from;
$$;The two updates run first. The final SELECT provides the return value, and it sees the changes made by the earlier statements in the same function.
All statements in the call run inside the caller's transaction. If any statement raises an error, the whole transaction aborts, and every earlier change is rolled back with it, unless the caller used a savepoint. A function cannot commit or roll back by itself. Procedures can control transactions in some cases, and a later section covers them.
Data-modifying CTEs inside a function
A common pattern is to use a data-modifying common table expression (CTE) so that one statement does several writes and returns a value:
-- Assumes tables orders(id serial primary key, customer_id int, total numeric)
-- and order_log(order_id int, note text)
CREATE FUNCTION place_order(p_customer int, p_total numeric)
RETURNS int
LANGUAGE sql
AS $$
WITH new_order AS (
INSERT INTO orders (customer_id, total)
VALUES (p_customer, p_total)
RETURNING id
), logged AS (
INSERT INTO order_log (order_id, note)
SELECT id, 'created' FROM new_order
)
SELECT id FROM new_order;
$$;PostgreSQL runs data-modifying CTEs exactly once, whether or not the main query reads them. Here the logged CTE is never referenced, and it still runs. The main query returns the id from new_order. Because this is one statement, it avoids the question of which statement produces the result.
Volatility for data-modifying functions
A function that writes data must be VOLATILE, which is the default. PostgreSQL rejects an INSERT, UPDATE or DELETE inside a function declared STABLE or IMMUTABLE. You get an error such as INSERT is not allowed in a non-volatile function.
Do not try to work around this. The planner may call a STABLE function fewer times than the query text suggests, and it may evaluate an IMMUTABLE function once at planning time. Either would silently skip or repeat your writes. Leave data-modifying functions as VOLATILE.
A related point: a VOLATILE function is never inlined into the calling query. A function that only reads data can be inlined under the rules in a later chapter.
Calling a data-modifying function
You can call these functions in a SELECT list, and they run once per row that the query produces:
SELECT create_customer(name, email)
FROM staging_customers;This works, and it creates one customer per staging row. It is also easy to misuse. Consider these cases:
- Calling the function in a
WHEREclause can run it many times, and the number of calls depends on the plan. - Calling it in a query that the planner might run more than once, such as inside a subquery, repeats the writes.
- A
SELECTthat usesLIMITmay run the function for fewer rows than you expect, or for more.
When you want to apply a write to a set of rows, a single INSERT ... SELECT is usually clearer and faster than calling a function per row. Reserve per-row calls for cases where the function adds real logic.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `return type mismatch in function declared to return integer` | The last statement is an `INSERT` with no `RETURNING`, or returns a different type. | Add `RETURNING id`, or declare `RETURNS void`. |
| `INSERT is not allowed in a non-volatile function` | The function is marked `STABLE` or `IMMUTABLE`. | Remove the marking so it is `VOLATILE`. |
| `column reference "id" is ambiguous` | A `RETURNS TABLE` column has the same name as a table column. | Qualify columns with a table alias. |
| Function returns `NULL` or no rows | The `WHERE` clause matched nothing. | Check for this case in the caller. |
| A write ran twice or not at all | The function was called in a `WHERE` clause or a subquery. | Call it once, in the select list or in a CTE. |
Security and permissions
A data-modifying function runs with the privileges of the caller, unless it is declared SECURITY DEFINER. The caller therefore needs INSERT rights on the target table. A later chapter explains how SECURITY DEFINER lets a function write to a table that the caller cannot write to directly, and how to do that safely.
Always pass values as parameters. Never build SQL by concatenating text. A plain SQL function body is fixed at creation time, so parameters are treated as values and not as SQL text. That protects you from SQL injection inside the function.
Choosing between functions and procedures
A function that changes data can be called from within a query. That is useful, and it also makes the function easy to misuse. If the operation is a standalone action, such as archiving old rows, a procedure and CALL fit better. The next chapter covers procedures.
Exercise
A function is declared RETURNS int LANGUAGE sql STABLE and its only statement is INSERT INTO customers (name) VALUES (p_name) RETURNING id;. What happens when you create it, and how do you fix it?
Show answer
PostgreSQL rejects the function, because an INSERT is not allowed in a STABLE function. Remove the STABLE keyword so the function is VOLATILE, which is the default. The RETURNING id clause is correct, since the last statement then supplies the int result.
Exercise
A function runs UPDATE accounts SET balance = balance - p_amount WHERE id = p_from; as its only statement and is declared RETURNS numeric. Why does it fail, and what is one way to fix it?
Show answer
The last statement must produce the declared return type, and an UPDATE without RETURNING produces no rows. Add RETURNING balance to return the new balance, or change the declaration to RETURNS void.