Sub topic 6
Running SQL inside a function
This chapter assumes you can write a basic CREATE FUNCTION ... LANGUAGE plpgsql block with DECLARE, BEGIN, and END. It also assumes you know how to declare variables and read parameters. You should be comfortable with SELECT, INSERT, UPDATE, and DELETE. The examples use customers(id, email, active) and orders(id, customer_id, total, created_at).
SQL is part of the language
PL/pgSQL has no separate database API. You write SQL statements directly in the function body, and PL/pgSQL sends them to the same executor that runs your ad hoc queries. Variables and parameters are passed in as query parameters, not pasted in as text. That gives you protection from SQL injection for values. It also means a variable can stand in for a value, never for a table or column name. Dynamic names need EXECUTE, which is a later chapter.
How you write a statement depends on whether you need its result:
- A command with no result to capture (
INSERT,UPDATE,DELETE, DDL) is written as it is. - A query whose single row you want goes through
SELECT ... INTO. - A query whose result you want to throw away goes through
PERFORM. - The number of rows a command touched comes from
FOUNDorGET DIAGNOSTICS.
SELECT INTO
SELECT ... INTO copies the columns of the first result row into variables. The INTO clause can sit right after the select list.
CREATE FUNCTION customer_summary(p_id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_email text;
v_orders bigint;
BEGIN
SELECT c.email, count(o.id)
INTO v_email, v_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE c.id = p_id
GROUP BY c.email;
IF NOT FOUND THEN
RETURN NULL;
END IF;
RETURN v_email || ' (' || v_orders || ' orders)';
END;
$$;The targets are matched to the select list by position, not by name. Use a record variable or a %ROWTYPE variable when you want the whole row in one target.
What happens with zero or many rows
Without STRICT, SELECT INTO is forgiving in a way that hides bugs:
- If the query returns no rows, every target is set to
NULL. - If it returns several rows, the first row is used and the rest are silently discarded. "First" is only defined if you add
ORDER BY.
Adding STRICT makes the statement demand exactly one row. Zero rows raises NO_DATA_FOUND. More than one row raises TOO_MANY_ROWS. The chapter's lookup function uses it to turn a missing customer into a clear message:
CREATE FUNCTION get_customer_email(p_id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_email text;
BEGIN
SELECT email INTO STRICT v_email
FROM customers
WHERE id = p_id;
RETURN v_email;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE EXCEPTION 'customer % not found', p_id;
END;
$$;Use STRICT when the row must exist and be unique, such as a lookup by primary key. Skip it when "no row" is a normal outcome you handle with FOUND.
SELECT without INTO
A bare SELECT inside a function has nowhere to send its rows. PL/pgSQL rejects it with query has no destination for result data. If you call a function only for its side effect, or you want the query run and its rows dropped, use PERFORM.
PERFORM
PERFORM takes the place of the word SELECT. The query runs, and its result is discarded.
CREATE FUNCTION lock_customer(p_id integer)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
PERFORM pg_advisory_xact_lock(p_id);
PERFORM 1 FROM customers WHERE id = p_id FOR UPDATE;
IF NOT FOUND THEN
RAISE EXCEPTION 'customer % not found', p_id;
END IF;
END;
$$;The first PERFORM calls a function for its side effect, an advisory lock held until the transaction ends. The second locks a row and uses FOUND to learn whether the row existed. For a plain existence test with no lock, IF EXISTS (SELECT 1 FROM ...) THEN is shorter.
Data-changing statements
INSERT, UPDATE, and DELETE are written as in plain SQL, with variables used as values. Add RETURNING ... INTO to capture generated values.
CREATE FUNCTION create_order(p_customer_id integer, p_total numeric)
RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
v_id integer;
BEGIN
INSERT INTO orders (customer_id, total, created_at)
VALUES (p_customer_id, p_total, now())
RETURNING id INTO v_id;
RETURN v_id;
END;
$$;There is one difference from SELECT INTO. For INSERT, UPDATE, or DELETE with RETURNING, PL/pgSQL raises an error if more than one row comes back, even without STRICT. An UPDATE ... RETURNING ... INTO that touches many rows therefore fails instead of silently keeping the first.
FOUND
FOUND is a boolean variable that exists in every function. Each statement resets it, so read it right after the statement you care about.
| Statement | Sets FOUND to true when |
|---|---|
| `SELECT INTO` | a row was assigned to the target |
| `PERFORM` | the query produced at least one row |
| `INSERT`, `UPDATE`, `DELETE` (including with `RETURNING`) | at least one row was affected |
| `FOR` loop over a query | the loop ran at least once |
| `RETURN QUERY` | at least one row was returned |
FOUND starts as false at the start of each function call. A common use is an UPDATE that must hit a row:
CREATE FUNCTION deactivate_customer(p_id integer)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
UPDATE customers SET active = false WHERE id = p_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'customer % not found', p_id;
END IF;
END;
$$;GET DIAGNOSTICS
FOUND only says whether anything happened. GET DIAGNOSTICS reports how much. The item ROW_COUNT holds the number of rows processed by the most recent SQL command.
CREATE FUNCTION deactivate_inactive(p_cutoff date)
RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
v_rows integer;
BEGIN
UPDATE customers c
SET active = false
WHERE c.active
AND NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id AND o.created_at >= p_cutoff
);
GET DIAGNOSTICS v_rows = ROW_COUNT;
RETURN v_rows;
END;
$$;Call GET DIAGNOSTICS immediately after the command. Any intervening SQL statement overwrites the value. The archive procedure in the stored procedures chapter relies on this pattern to know when its batches are finished.
Name conflicts between variables and columns
Parameters, variables, and the output columns of RETURNS TABLE all live in the same namespace as the columns of your queries. When a name could be either, PL/pgSQL raises an error instead of guessing.
CREATE FUNCTION find_customer_id(email text)
RETURNS integer
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_id integer;
BEGIN
SELECT id INTO v_id FROM customers WHERE email = email;
RETURN v_id;
END;
$$;Calling this function fails with column reference "email" is ambiguous. The parameter email and the column customers.email both match. You have three ways out:
- Prefix parameters and variables, for example
p_emailandv_id. This is the convention used throughout this tutorial and is the most readable. - Qualify every column with a table alias (
c.email), and qualify the parameter with the function name (find_customer_id.email) when you cannot rename it. - Put
#variable_conflict use_columnor#variable_conflict use_variableat the start of the function body to pick a winner. This works but hides mistakes, so prefer renaming.
The same rule explains why the RETURNS TABLE example qualifies columns with the alias o. The output column total is a variable, and an unqualified total would be ambiguous.
Common errors
- Reading
FOUNDafter another statement has run, such as aRAISE NOTICEwith a query inside it. - Forgetting
ORDER BYon a non-strictSELECT INTOthat can match many rows, which gives an arbitrary row. - Counting on
STRICTfor anUPDATE.UPDATE ... INTO STRICTis allowed only withRETURNING, so useFOUNDorROW_COUNTfor plain updates. - Using a variable as a table name.
SELECT * FROM v_tablelooks for a table literally calledv_table.
Exercise
A function runs SELECT email INTO v_email FROM customers WHERE active ORDER BY id LIMIT 1; (no STRICT) and the customers table has no active customers. What are v_email and FOUND afterward? How would the result differ if you added STRICT?
Show answer
Without STRICT, vemail is set to NULL and FOUND is false, and no error is raised. With STRICT, the zero-row result raises NODATA_FOUND, so the function stops with an error unless an EXCEPTION block handles it.
Exercise
Write the body of a function that deletes all orders for a given customer pcustomerid and returns how many rows were deleted. Which diagnostic item do you use, and where must you call it?
Show answer
DELETE FROM orders WHERE customerid = pcustomerid; GET DIAGNOSTICS vrows = ROWCOUNT; RETURN vrows; with vrows declared as integer. GET DIAGNOSTICS must come immediately after the DELETE, because the next SQL command replaces the ROWCOUNT value.