Sub topic 3
Variables, Constants, and Copied Types with `%TYPE` and `%ROWTYPE`
Assume you know basic SQL, PostgreSQL table types, and programming concepts such as variables and loops. This chapter shows how PL/pgSQL stores intermediate values and how declarations can stay synchronized with table definitions.
Declaring variables
A PL/pgSQL function has a declaration section between DECLARE and BEGIN. Each declaration gives a variable a name and data type. You can optionally assign an initial value.
CREATE TABLE customers (
id integer PRIMARY KEY,
email text NOT NULL,
credit_limit numeric(10, 2) NOT NULL
);
CREATE FUNCTION customer_credit_limit(p_customer_id integer)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_limit numeric(10, 2);
BEGIN
SELECT c.credit_limit
INTO v_limit
FROM customers AS c
WHERE c.id = p_customer_id;
RETURN v_limit;
END;
$$;The variable v_limit exists only while the function runs. The SELECT INTO statement assigns the selected value to it. In PL/pgSQL, SELECT INTO means “put the query result into variables,” unlike SQL's table-creation form of SELECT INTO.
Variables can have default values. The expression is evaluated when the block begins.
DECLARE
v_total numeric := 0;
v_started_at timestamptz := now();A variable with no assigned value starts as NULL. Use COALESCE or an explicit default when NULL would cause incorrect calculations.
Constants
A constant is a variable that cannot be assigned a new value after initialization. Declare it with CONSTANT.
CREATE FUNCTION calculate_fee(p_amount numeric)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
c_fee_rate CONSTANT numeric := 0.025;
BEGIN
RETURN round(p_amount * c_fee_rate, 2);
END;
$$;The initializer is required for a constant. Attempting to assign c_fee_rate := 0.03 later raises an error. Constants are useful for values that must remain fixed during a function call, such as a business rule or a conversion factor.
Copying a column type with `%TYPE`
The %TYPE attribute copies a column's data type into a variable declaration.
CREATE FUNCTION customer_email(p_customer_id customers.id%TYPE)
RETURNS customers.email%TYPE
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_email customers.email%TYPE;
BEGIN
SELECT c.email
INTO v_email
FROM customers AS c
WHERE c.id = p_customer_id;
RETURN v_email;
END;
$$;Here, the parameter and return value follow the types of customers.id and customers.email. If the table changes from integer to another compatible type, the function declaration does not contain a duplicated type that can become stale.
%TYPE copies the type, but not every column property. It does not automatically copy NOT NULL, default expressions, or constraints into a local variable.
Copying a row shape with `%ROWTYPE`
The %ROWTYPE attribute creates a variable with one field for every column in a table row.
CREATE FUNCTION get_customer(p_customer_id integer)
RETURNS customers
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_customer customers%ROWTYPE;
BEGIN
SELECT c.*
INTO v_customer
FROM customers AS c
WHERE c.id = p_customer_id;
RETURN v_customer;
END;
$$;Access a field with dot notation, such as v_customer.email. A %ROWTYPE variable is useful when several columns must travel together. It also reduces repeated declarations, but it couples the function to the table's row shape.
Common errors
- Forgetting that an uninitialized variable is
NULL. - Selecting multiple rows into a scalar variable without deciding which row is intended.
- Using
%ROWTYPEwhen a small, stable result would make the function easier to understand. - Assuming
%TYPEcopies constraints as well as the base data type. - Naming variables like columns and then misreading an ambiguous query. Qualify table columns with aliases, such as
c.email.
Exercise
Which declaration should you use for a variable that stores the email column from customers and should follow future changes to that column's type?
Show answer
Use v_email customers.email%TYPE;.