Sub topic 1
What PL/pgSQL Is and When to Use It
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), can run statements in psql or another client, and understand simple variables and conditionals. You should also have a PostgreSQL database you can write to.
What PL/pgSQL Is
PL/pgSQL is PostgreSQL's built-in procedural language. It lets you store logic in the database as a function, so the database runs the steps for you. Use it when several SQL statements must run together, when logic needs variables or conditionals, or when many applications must share one rule.
Use plain SQL when one statement can do the job. Plain SQL is simpler to read and often faster.
Your First Function
A function is a named, reusable piece of code. The following function adds tax to a price. The DEFAULT clause makes the rate optional.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
AS $$
DECLARE
total numeric;
BEGIN
total := round(price * (1 + rate), 2);
RETURN total;
END;
$$;
SELECT add_tax(100);
SELECT add_tax(100, rate => 0.07);The DECLARE section holds variables. The BEGIN and END section holds statements. The $$ markers quote the body, so you do not need to escape its quotes.
Variables, Constants, and Copied Types
A constant cannot change after it is set. Use CONSTANT to declare one.
%TYPE copies the type of a column, so the variable still works if the column type changes later. %ROWTYPE copies the whole row layout of a table.
DECLARE
c_rate CONSTANT numeric := 0.2;
v_email customers.email%TYPE;
r customers%ROWTYPE;Parameters: OUT and INOUT
An OUT parameter is a result you return by name. An INOUT parameter is read on entry and changed on exit.
CREATE FUNCTION split_total(IN amount numeric, OUT whole numeric, OUT cents numeric)
LANGUAGE plpgsql
AS $$
BEGIN
whole := trunc(amount);
cents := round((amount - trunc(amount)) * 100);
END;
$$;
SELECT * FROM split_total(12.34);Functions with OUT parameters do not need a RETURNS clause.
Exercise
Write a function double_it(n integer) that returns n * 2. What does SELECT double_it(4); return?
Show answer
The function returns 8. Use CREATE FUNCTION double_it(n integer) RETURNS integer LANGUAGE plpgsql AS $$ BEGIN RETURN n * 2; END; $$;