Sub topic 2
NULL inputs and STRICT
This chapter assumes you know SELECT, INSERT and CREATE TABLE, and that you can run statements in psql. It covers NULL handling, set-returning functions, volatility, and functions that change data.
How NULL reaches a function
NULL means "no value". Most SQL operators return NULL when any input is NULL. By default, a SQL function runs its body even when an argument is NULL, so the body must handle that case itself.
Using STRICT
STRICT tells PostgreSQL to skip the body when any argument is NULL. The call returns NULL immediately.
CREATE FUNCTION full_name(first_name text, last_name text)
RETURNS text
LANGUAGE sql
IMMUTABLE STRICT
AS $$
SELECT first_name || ' ' || last_name;
$$;
SELECT full_name('Ada', 'Lovelace'); -- Ada Lovelace
SELECT full_name('Ada', NULL); -- NULL, body not runUse STRICT when a NULL input makes the result meaningless. Use COALESCE in the body when NULL should produce a default value instead.
Returning rows with SETOF and RETURNS TABLE
A set-returning function returns zero or more rows. RETURNS TABLE names each output column.
CREATE TABLE orders (
id int PRIMARY KEY,
customer_id int NOT NULL,
ordered_at timestamptz NOT NULL,
total numeric NOT NULL
);
CREATE FUNCTION recent_orders(p_customer_id int, p_limit int DEFAULT 10)
RETURNS TABLE (order_id int, ordered_at timestamptz, total numeric)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, o.ordered_at, o.total
FROM orders AS o
WHERE o.customer_id = p_customer_id
ORDER BY o.ordered_at DESC
LIMIT p_limit;
$$;
SELECT * FROM recent_orders(42, 5);Declaring volatility correctly
Volatility tells the planner how predictable a function's result is.
| Category | Meaning | Example |
|---|---|---|
| IMMUTABLE | Same input always gives the same output | full_name |
| STABLE | Same output within one statement, may read tables | recent_orders |
| VOLATILE | May change on every call, and is the default | create_customer |
Functions that change data
A function that modifies data must stay VOLATILE. Use INSERT ... RETURNING as the last statement so the function returns the new value.
CREATE TABLE customers (
id serial PRIMARY KEY,
name text NOT NULL,
email text NOT NULL
);
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]');Exercise
Exercise
You write a function that inserts a row into a log table and returns the new id. Which volatility should you declare?
Show answer
Leave the default, VOLATILE. The function writes data, so it must not be declared STABLE or IMMUTABLE.