Sub topic 8
Functions That Change Data
This chapter assumes you know basic INSERT, UPDATE, and DELETE statements, PostgreSQL types, and how to run SQL from a client. The examples use SQL-language functions. These functions execute SQL statements and can return a value to the caller.
Use `RETURNING` for a function result
A SQL function can change data. If the function returns a non-void value, its final statement must produce that value. A data-modifying statement can do this with RETURNING.
CREATE TEMP TABLE customers (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
email text NOT NULL
);
CREATE FUNCTION create_customer(p_name text, p_email text)
RETURNS integer
LANGUAGE sql
AS $$
INSERT INTO customers (name, email)
VALUES (p_name, p_email)
RETURNING id;
$$;
SELECT create_customer('Ada Lovelace', '[email protected]');The INSERT changes the table and returns the generated id. Because it is the final statement, that id becomes the function result.
The function call is an expression, so you can use it in a larger statement:
SELECT create_customer('Grace Hopper', '[email protected]')
AS new_customer_id;You can use the same pattern with UPDATE or DELETE:
CREATE FUNCTION rename_customer(p_id integer, p_name text)
RETURNS text
LANGUAGE sql
AS $$
UPDATE customers
SET name = p_name
WHERE id = p_id
RETURNING name;
$$;If no row matches, the UPDATE ... RETURNING query produces no row. For a scalar SQL function, that normally results in a NULL function result. If multiple rows could match, the function may fail because a scalar result cannot contain multiple rows. Make the input unique or return a set when multiple rows are valid.
Functions and procedures have different roles
A function is called inside an expression, such as SELECT create_customer(...). A procedure is called with CALL and is better suited to a sequence of commands whose main purpose is an operation rather than a value.
A procedure can run several data-changing statements in order:
CREATE PROCEDURE archive_customer(p_id integer)
LANGUAGE sql
AS $$
INSERT INTO customer_archive
SELECT *
FROM customers
WHERE id = p_id;
DELETE FROM customers
WHERE id = p_id;
$$;
CALL archive_customer(1);This assumes customer_archive has compatible columns. The procedure does not return the deleted row as an expression result. Its purpose is the sequence of side effects.
Choose a function when the caller needs a result, especially an inserted identifier or updated value. Choose a procedure when the caller wants an operation composed of multiple statements and does not need that operation to be embedded in a query.
Exercise
Why must a scalar function using INSERT usually end with INSERT ... RETURNING?
Show answer
The final statement supplies the scalar value that the function returns. Without RETURNING, INSERT changes data but does not produce the required result.