Sub topic 2
Control flow: IF, CASE, and loops
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, JOIN), can run CREATE FUNCTION in psql, and understand variables and conditionals in another language.
Branching with IF and CASE
IF runs a block only when a condition is true. Use ELSIF for further tests.
CREATE FUNCTION grade_label(p_score integer)
RETURNS text
LANGUAGE plpgsql
AS $$
BEGIN
IF p_score >= 90 THEN
RETURN 'excellent';
ELSIF p_score >= 60 THEN
RETURN 'pass';
ELSE
RETURN 'fail';
END IF;
END;
$$;CASE compares one value against a list of options. It works well inside a RETURN statement.
CREATE FUNCTION day_type(p_day integer)
RETURNS text
LANGUAGE plpgsql
AS $$
BEGIN
RETURN CASE p_day
WHEN 6, 7 THEN 'weekend'
ELSE 'weekday'
END;
END;
$$;Loops
A FOR loop over an integer range runs a fixed number of times. LOOP with EXIT WHEN runs until a condition is met.
CREATE FUNCTION sum_to(p_n integer)
RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
v_total integer := 0;
BEGIN
FOR i IN 1..p_n LOOP
v_total := v_total + i;
END LOOP;
RETURN v_total;
END;
$$;Running SQL inside a function
SELECT ... INTO stores one row's values in variables. Afterward, the special variable FOUND is true if a row was returned.
CREATE FUNCTION get_customer_email(p_id integer)
RETURNS text
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_email text;
BEGIN
SELECT email INTO v_email FROM customers WHERE id = p_id;
IF NOT FOUND THEN
RETURN NULL;
END IF;
RETURN v_email;
END;
$$;Returning rows and sets
RETURNS TABLE declares the output columns. RETURN QUERY adds the rows of a query to the result.
CREATE FUNCTION orders_over(p_min numeric)
RETURNS TABLE (order_id integer, total numeric)
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
RETURN QUERY
SELECT o.id, o.total
FROM orders o
WHERE o.total > p_min
ORDER BY o.id;
END;
$$;Looping over query results
A FOR ... IN query LOOP reads results one row at a time. Each loop variable r holds one row.
CREATE FUNCTION total_for_customer(p_customer_id integer)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r record;
v_sum numeric := 0;
BEGIN
FOR r IN SELECT o.total FROM orders o WHERE o.customer_id = p_customer_id LOOP
v_sum := v_sum + r.total;
END LOOP;
RETURN v_sum;
END;
$$;Exercise
Rewrite totalforcustomer without a loop. Return 0 when the customer has no orders.
Show answer
SELECT coalesce(sum(total), 0) FROM orders WHERE customerid = pcustomerid; The function body becomes RETURN (SELECT coalesce(sum(total), 0) FROM orders WHERE customerid = pcustomerid); and the loop and variables are removed.