Sub topic 5
Control flow: IF, CASE, and loops
This chapter covers the statements that decide which code runs and how many times: IF, CASE, and the loop forms of PL/pgSQL. It assumes you can write a basic CREATE FUNCTION ... LANGUAGE plpgsql body with a DECLARE section, assign with :=, and run it from psql. Looping over query results gets its own chapter, so loops here work on numbers and conditions.
Choosing a branch with IF
IF has three forms: IF ... THEN ... END IF, with an optional ELSE, and with any number of ELSIF branches. The first branch whose condition is true runs. The rest are skipped.
CREATE FUNCTION shipping_class(p_weight_kg numeric)
RETURNS text
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
IF p_weight_kg IS NULL THEN
RETURN 'unknown';
ELSIF p_weight_kg <= 1 THEN
RETURN 'letter';
ELSIF p_weight_kg <= 20 THEN
RETURN 'parcel';
ELSE
RETURN 'freight';
END IF;
END;
$$;
SELECT shipping_class(0.5), shipping_class(12), shipping_class(NULL);The keyword is ELSIF, with one E. ELSEIF is accepted as a synonym, but ELSE IF is not. It opens a new nested IF that needs its own END IF.
Choosing a value with CASE
PL/pgSQL has two different things called CASE. The CASE statement runs statements. The CASE expression is SQL and produces a value. Both come in a simple form, which compares one value against a list, and a searched form, which evaluates independent boolean conditions.
CREATE FUNCTION discount_rate(p_tier text)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
v_rate numeric;
BEGIN
CASE p_tier
WHEN 'gold' THEN
v_rate := 0.15;
WHEN 'silver', 'bronze' THEN
v_rate := 0.05;
ELSE
v_rate := 0;
END CASE;
RETURN v_rate;
END;
$$;
SELECT discount_rate('gold'), discount_rate('bronze'), discount_rate('none');The searched form drops the value after CASE and puts a full condition after each WHEN:
CREATE FUNCTION age_band(p_age integer)
RETURNS text
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
CASE
WHEN p_age < 0 THEN
RAISE EXCEPTION 'age cannot be negative: %', p_age;
WHEN p_age < 18 THEN
RETURN 'minor';
WHEN p_age < 65 THEN
RETURN 'adult';
ELSE
RETURN 'senior';
END CASE;
END;
$$;Inside a query you still use the SQL expression, for example SELECT CASE WHEN total > 500 THEN 'large' ELSE 'small' END FROM orders. Use it whenever the choice is part of a row's value. Use IF or the CASE statement when the choice changes which statements execute.
The basic LOOP, EXIT, and CONTINUE
LOOP ... END LOOP repeats forever until something leaves it. EXIT leaves the loop. EXIT WHEN condition is the usual shorthand for IF condition THEN EXIT; END IF. CONTINUE skips the rest of the current iteration and starts the next one.
CREATE FUNCTION first_square_over(p_limit integer)
RETURNS integer
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
n integer := 0;
BEGIN
LOOP
n := n + 1;
EXIT WHEN n * n > p_limit;
END LOOP;
RETURN n;
END;
$$;
SELECT first_square_over(50); -- 8, because 8 * 8 = 64A plain LOOP with no reachable EXIT runs until you cancel the query or hit statement_timeout. Check that the exit condition can become true for every input, including NULL.
WHILE loops
WHILE condition LOOP tests the condition before each iteration, so the body may run zero times. As with IF, a NULL condition counts as false and the loop ends or never starts.
CREATE FUNCTION collatz_steps(p_start bigint)
RETURNS integer
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
n bigint := p_start;
steps integer := 0;
BEGIN
IF p_start IS NULL OR p_start < 1 THEN
RAISE EXCEPTION 'start must be a positive number, got %', p_start;
END IF;
WHILE n <> 1 LOOP
IF n % 2 = 0 THEN
n := n / 2;
ELSE
n := 3 * n + 1;
END IF;
steps := steps + 1;
END LOOP;
RETURN steps;
END;
$$;
SELECT collatz_steps(6); -- 8The guard at the top matters. Without it, a NULL input would skip the loop and return 0, and a zero or negative input would loop forever.
Counting with FOR
The integer FOR loop declares its counter automatically. The counter exists only inside the loop and shadows any variable of the same name. The bounds are evaluated once, before the first iteration. BY sets the step. With REVERSE you write the larger bound first.
CREATE FUNCTION odd_sum(p_max integer)
RETURNS integer
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
v_sum integer := 0;
BEGIN
FOR i IN 1..p_max LOOP
CONTINUE WHEN i % 2 = 0;
v_sum := v_sum + i;
END LOOP;
RETURN v_sum;
END;
$$;
SELECT odd_sum(10); -- 25| Form | Meaning |
|---|---|
| `FOR i IN 1..5 LOOP` | 1, 2, 3, 4, 5 |
| `FOR i IN 1..10 BY 3 LOOP` | 1, 4, 7, 10 |
| `FOR i IN REVERSE 5..1 LOOP` | 5, 4, 3, 2, 1 |
| `FOR i IN 5..1 LOOP` | Runs zero times, because the range is empty |
A NULL bound raises an error at run time. To walk the elements of an array, use FOREACH x IN ARRAY some_array LOOP ... END LOOP;, where x is a declared variable of the element type.
Labels and nested loops
EXIT and CONTINUE apply to the innermost loop. To act on an outer loop, put a label before it in double angle brackets and name it in the statement.
CREATE FUNCTION smallest_factor_pair(p_target integer)
RETURNS text
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
v_a integer;
v_b integer;
BEGIN
<<outer_loop>>
FOR a IN 2..p_target LOOP
FOR b IN a..p_target LOOP
EXIT WHEN a * b > p_target;
IF a * b = p_target THEN
v_a := a;
v_b := b;
EXIT outer_loop;
END IF;
END LOOP;
END LOOP;
IF v_a IS NULL THEN
RETURN 'none';
END IF;
RETURN format('%s x %s', v_a, v_b);
END;
$$;
SELECT smallest_factor_pair(12), smallest_factor_pair(13); -- '2 x 6', 'none'The loop counters a and b vanish when their loops end. That is why the function copies the result into v_a and v_b, which are declared in the outer block, before leaving. The inner EXIT WHEN stops useless work once the product is too big. EXIT outer_loop leaves both loops at once.
Choosing between loops and SQL
Loops are procedural. PostgreSQL runs them one iteration at a time, and every SQL statement inside a loop is planned and executed per iteration. For counting, summing, or filtering rows, a single set-based statement is nearly always faster than a loop. Use loops for work that is inherently sequential, such as retry logic, walking a numeric sequence, or batching.
Common errors
- Writing
ELSE IFand gettingsyntax erroror a missingEND IF. UseELSIF. - Forgetting the semicolon after
END IF,END CASE, orEND LOOP. Each requires one. - Reading a FOR counter after its loop, which fails with
column "i" does not exist. Copy it into a declared variable inside the loop. - Using a CASE statement without
ELSEand gettingcase not found. - Writing a loop whose exit condition depends on a value that can be NULL.
Exercise
What do shipping_class(NULL) and a version of the function that has no IS NULL branch but starts with IF p_weight_kg <= 1 THEN return when passed NULL? Which branch runs in the second version, and why?
Show answer
The shown function returns 'unknown' because of its explicit IS NULL branch. In the second version, NULL <= 1 evaluates to NULL, and IF treats NULL as false. Each ELSIF is also NULL, so control falls through to the final ELSE and returns 'freight'. The fix is to test IS NULL first.
Exercise
Write a function countdown(p_from integer) that returns text such as '3-2-1' for input 3, using a FOR loop with REVERSE. What does it return for an input of 0?
Show answer
One solution:
CREATE FUNCTION countdown(pfrom integer) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $$ DECLARE vout text := ''; BEGIN FOR i IN REVERSE pfrom..1 LOOP vout := vout || CASE WHEN vout = '' THEN '' ELSE '-' END || i::text; END LOOP; RETURN v_out; END; $$;
For input 3 it returns '3-2-1'. For 0 the range 0..1 read in reverse is empty, so the loop runs zero times and the function returns an empty string.