Part 13 / Topic 5 of 8
PL/pgSQL
When logic needs variables, branches and loops, the language is PL/pgSQL. A stock-check that explains itself:
CREATE FUNCTION restock_advice(p_product_id integer)
RETURNS text
LANGUAGE plpgsql STABLE
AS $$
DECLARE
v_name text;
v_stock integer;
BEGIN
SELECT name, stock INTO v_name, v_stock
FROM products WHERE product_id = p_product_id;
IF NOT FOUND THEN
RETURN 'no such product';
ELSIF v_stock = 0 THEN
RETURN v_name || ': OUT OF STOCK - reorder now';
ELSIF v_stock < 20 THEN
RETURN v_name || ': low (' || v_stock || ' left)';
ELSE
RETURN v_name || ': fine (' || v_stock || ')';
END IF;
END;
$$;
SELECT restock_advice(8) AS coffee_maker,
restock_advice(2) AS laptop_air,
restock_advice(999) AS ghost;
CREATE FUNCTION
coffee_maker | laptop_air | ghost
------------------------------------------+-----------------------------+-----------------
Coffee Maker: OUT OF STOCK - reorder now | Laptop Air 13: low (8 left) | no such product
(1 row)
The toolbox in that one function: DECLARE variables, SELECT ... INTO, the magic FOUND flag, IF/ELSIF. Add FOR r IN SELECT ... LOOP ... END LOOP; for iteration and RAISE NOTICE 'debug %', v; for printf-debugging, and you have ninety percent of the PL/pgSQL you'll ever read. Rule of taste: if it can be a single SQL statement, it should be — PL/pgSQL is for genuine branching, not for spelling out what a join would do better.
🧪 Quick quiz — answer from memory, then check.
- What does
FOUNDtell you afterSELECT ... INTO? - When should logic not be PL/pgSQL?
Show the answers
- Whether the query actually returned a row (if it is false, your variables hold NULLs).
- When one set-based SQL statement can do it — the loop you didn't write is the fastest loop.
Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.