Sub topic 3
Variables, constants, and copying types with %TYPE and %ROWTYPE
This chapter assumes you can write a basic CREATE FUNCTION ... LANGUAGE plpgsql with a DECLARE section and a BEGIN ... END body. You should also be comfortable with SELECT ... INTO at a basic level. The chapter covers how to declare variables and constants, how scope and name resolution work, and how to make variables follow the types of your tables.
The examples use two small tables.
CREATE TABLE customers (
id integer PRIMARY KEY,
email text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
total numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);Declaring variables
Every variable lives in the DECLARE section of a block. A declaration has a name, a type, and optional modifiers.
name [ CONSTANT ] type [ COLLATE collation ] [ NOT NULL ] [ { DEFAULT | := | = } expression ];The three initializer forms DEFAULT, :=, and = are equivalent. Most code uses :=, so this tutorial does too.
CREATE FUNCTION order_summary(p_order_id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
c_vat_rate CONSTANT numeric := 0.20;
v_label text NOT NULL DEFAULT 'order';
v_total orders.total%TYPE;
BEGIN
SELECT total INTO STRICT v_total
FROM orders
WHERE id = p_order_id;
RETURN format('%s %s: %s incl. VAT',
v_label, p_order_id, round(v_total * (1 + c_vat_rate), 2));
END;
$$;Four rules apply here:
- A variable without an initializer starts as
NULL. This happens on every call, because variables are created fresh each time the block is entered. State does not carry over between calls. - A
CONSTANTmust have an initial value, and assigning to it later is a compile-time error. - A
NOT NULLvariable must also have an initial value. AssigningNULLto it later raises an error at run time. - The initial value can be any expression, including one that uses earlier variables or parameters in the same
DECLAREsection.
The prefixes p_, v_, and c_ are a convention, not a language feature. The next sections show why the parameter prefix matters.
Assigning values
There are three common ways to assign a value:
v_x := expression;assigns the result of an expression.SELECT ... INTO v_x ...assigns the result of a query.GET DIAGNOSTICS v_x = ROW_COUNT;assigns status information about the last statement.
An assignment with := can also run a scalar subquery.
v_total := (SELECT sum(total) FROM orders WHERE customer_id = p_customer_id);If the subquery returns no rows, the variable becomes NULL. If it returns more than one row, you get an error. SELECT INTO without STRICT behaves differently: it silently keeps the first row. Chapter topics on running SQL cover that choice in detail. Here, remember that a variable is only as strict as the statement that fills it.
Scope, nested blocks, and labels
A BEGIN ... END block can contain other blocks, and each block can have its own DECLARE section. A variable is visible from its declaration to the end of its block, including inner blocks. An inner variable with the same name as an outer one shadows it.
DO $$
<<outer_block>>
DECLARE
x integer := 1;
BEGIN
DECLARE
x integer := 2;
BEGIN
RAISE NOTICE 'inner x = %', x;
RAISE NOTICE 'outer x = %', outer_block.x;
END;
RAISE NOTICE 'x after the inner block = %', x;
END;
$$;This prints inner x = 2, outer x = 1, and x after the inner block = 1. The label <<outer_block>> goes before DECLARE and lets you reach a shadowed variable with label.name. The function's own name works as a label for its parameters and top-level variables, which becomes important in the next section.
The diagram is simplified. Inside an SQL statement, a name can match both a variable and a column. The next section covers that case.
Name conflicts between variables and columns
PL/pgSQL passes your SQL statements to the regular SQL engine, with variables substituted as parameters. If a variable has the same name as a column used in the statement, the engine cannot tell which one you mean. By default it raises an error rather than guessing.
CREATE FUNCTION find_customer_id(email text)
RETURNS integer
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
RETURN (SELECT c.id FROM customers c WHERE c.email = email);
END;
$$;
SELECT find_customer_id('[email protected]');
-- ERROR: column reference "email" is ambiguousThe function is created without complaint, because the conflict only appears when the statement is planned at run time. There are three fixes, in order of preference:
- Rename the parameter, for example
p_email. This avoids the problem everywhere. - Qualify the variable with the function name:
c.email = find_customer_id.email. - Set
#variable_conflict use_variableor#variable_conflict use_columnas the first line of the function body. This changes how conflicts resolve for the whole function, and it hides mistakes, so use it rarely.
The same clash happens with RETURNS TABLE and OUT column names, because they are variables too. That is why the orders_over example in the return types chapter qualifies every column with the table alias o.
Copying a column's type with %TYPE
table.column%TYPE declares a variable with the same data type as a column. You can also write variable%TYPE to copy the type of another variable or a parameter.
DECLARE
v_total orders.total%TYPE;
v_prev v_total%TYPE;The benefit is maintenance. If someone changes orders.total from numeric(10,2) to numeric(12,2), a hard-coded numeric(10,2) variable would be too small, but a %TYPE variable follows the column.
There are some limits to know:
- The type is resolved when the function is first run in a session, not when you create it. A session that already ran the function keeps working with the old type until it reconnects or the function is replaced.
- The table must exist when you create the function. If it does not,
CREATE FUNCTIONfails. - Functions do not register dependencies on the columns they mention.
ALTER TABLE ... DROP COLUMNsucceeds, and the function fails the next time it is compiled. %TYPEcopies only the data type. It does not copyNOT NULL, defaults, or check constraints.
Copying a row's shape with %ROWTYPE
table%ROWTYPE declares a variable that holds a whole row of that table. Its fields are the table's columns and are read with dot notation.
CREATE FUNCTION customer_label(p_id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_cust customers%ROWTYPE;
BEGIN
SELECT * INTO STRICT v_cust
FROM customers
WHERE id = p_id;
v_cust.email := lower(v_cust.email);
RETURN format('%s <%s>', v_cust.id, v_cust.email);
END;
$$;You can assign to a single field, as the lower() line does. You can also pass the whole variable on, for example as the source of an INSERT:
INSERT INTO customers SELECT v_cust.*;Every table in PostgreSQL has a matching composite type of the same name, so customers alone works as a type name too. customers%ROWTYPE and customers mean the same thing in a declaration, and the %ROWTYPE spelling is mainly there for readability and for compatibility with Oracle's PL/SQL.
The SELECT * pairing deserves care. If the column list of the query and the row type differ, which happens after an ALTER TABLE ADD COLUMN in an already-running session, the assignment can fail or mismatch. When you only need two columns, select just those columns into plain variables.
The record type
A record variable has no fixed shape. It takes the structure of whatever row is assigned to it.
DECLARE
r record;
BEGIN
SELECT c.id, c.email, count(o.id) AS order_count
INTO STRICT r
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE c.id = 1
GROUP BY c.id, c.email;
RAISE NOTICE '% has % orders', r.email, r.order_count;
END;Use record when the row comes from a join or an aggregate and no table matches it. A record has no structure until the first assignment, and reading a field before that raises record "r" is not assigned yet. A record can also be reassigned from a query with a different shape later in the same block, which %ROWTYPE variables cannot do.
Choosing a declaration
| Declaration | Shape is fixed by | Use it when |
|---|---|---|
| `v integer` | You | The value is not tied to a table, such as counters and flags |
| `v tbl.col%TYPE` | The column | The value is read from or written to that column |
| `v other%TYPE` | Another variable | Two variables must always have the same type |
| `v tbl%ROWTYPE` | The table | You select or modify a whole row of one table |
| `v record` | The first assignment | The row comes from a join, aggregate, or loop |
Common mistakes
- Using
=in a comparison and:=in an assignment, then mixing them up. In PL/pgSQL both forms assign, but only=compares inside expressions such asIF v_x = 1. Using:=consistently for assignment makes the code easier to read. - Declaring a variable without a prefix, then naming a column the same. See the conflict section above.
- Expecting a variable to keep its value across calls. It does not. Use a table or a custom setting for persistent state.
- Declaring
NOT NULLwithout an initializer, which is a compile-time error. - Using
%ROWTYPEfor a query that selects only some columns, which fails with a mismatch error.
Practice
Exercise
A function takes a parameter named total and runs SELECT id FROM orders WHERE total > total. What happens when it is called, and how do you fix it without changing the query's meaning?
Show answer
PostgreSQL raises "column reference "total" is ambiguous", because total matches both the parameter and the orders.total column. The fix is to rename the parameter to p_total and write WHERE total > p_total. Qualifying the parameter with the function name, as in fn_name.total, also works.
Exercise
Write a function latest_order_total(p_customer_id integer) that returns the total of the customer's most recent order. Declare the variable that holds the total so it follows the column's type, and raise an error if the customer has no orders.
Show answer
CREATE FUNCTION latestordertotal(pcustomerid integer) RETURNS numeric LANGUAGE plpgsql STABLE AS $$ DECLARE vtotal orders.total%TYPE; BEGIN SELECT o.total INTO STRICT vtotal FROM orders o WHERE o.customerid = pcustomerid ORDER BY o.createdat DESC, o.id DESC LIMIT 1; RETURN vtotal; EXCEPTION WHEN NODATAFOUND THEN RAISE EXCEPTION 'customer % has no orders', pcustomer_id; END; $$;
Exercise
Why does DECLARE c_rate CONSTANT numeric; fail, and why does DECLARE v_name text NOT NULL; fail?
Show answer
A constant can never be assigned after declaration, so it needs an initial value, as in c_rate CONSTANT numeric := 0.2. A NOT NULL variable cannot hold NULL, and without an initializer it would start as NULL, so it also requires an initial value, as in v_name text NOT NULL := 'unknown'.