Sub topic 5
Control Flow: IF, CASE, and Loops
Assume you know basic SQL and have seen the DECLARE, BEGIN, and END parts of a PL/pgSQL function. This chapter focuses on choosing paths and repeating work inside that block.
Control flow decides which statements run and how often they run. PL/pgSQL provides IF, CASE, and several loop forms.
Choosing between IF and CASE
Use IF when conditions are unrelated or when one condition contains another. Use CASE when you are selecting among several alternatives.
CREATE OR REPLACE FUNCTION classify_total(p_total numeric)
RETURNS text
LANGUAGE plpgsql
AS $$
DECLARE
v_label text;
BEGIN
IF p_total IS NULL THEN
RETURN 'unknown';
END IF;
CASE
WHEN p_total < 100 THEN
v_label := 'small';
WHEN p_total < 1000 THEN
v_label := 'medium';
ELSE
v_label := 'large';
END CASE;
RETURN v_label;
END;
$$;
SELECT classify_total(75); -- small
SELECT classify_total(450); -- medium
SELECT classify_total(NULL); -- unknownThis example uses a searched CASE, where each branch has a Boolean condition. A simple CASE compares one expression with several values:
CASE p_status
WHEN 'new' THEN v_message := 'Needs review';
WHEN 'paid' THEN v_message := 'Complete';
ELSE v_message := 'Other';
END CASE;An IF condition that evaluates to NULL is treated as not true, so its ELSE branch runs. Test IS NULL explicitly when NULL has a special meaning.
Repeating work with loops
Use LOOP when the stopping condition is easiest to express inside the loop. EXIT stops the loop, and CONTINUE skips to its next iteration. A WHILE loop checks its condition before every iteration. A numeric FOR loop counts through a known range.
CREATE OR REPLACE FUNCTION sum_odd_numbers(p_limit integer)
RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
v_number integer := 1;
v_sum integer := 0;
BEGIN
LOOP
EXIT WHEN v_number > p_limit;
IF v_number % 2 = 0 THEN
v_number := v_number + 1;
CONTINUE;
END IF;
v_sum := v_sum + v_number;
v_number := v_number + 1;
END LOOP;
RETURN v_sum;
END;
$$;
SELECT sum_odd_numbers(10); -- 25The EXIT WHEN check prevents an infinite loop. Every path through the loop must eventually change v_number or leave the loop.
| Construct | Best fit |
|---|---|
| `IF` | Different conditions or nested decisions |
| `CASE` | Several related alternatives |
| `WHILE` | Repeat while a condition remains true |
| `FOR` | Repeat over a numeric range or query result |
| `LOOP` | Custom stopping logic using `EXIT` |
Common control-flow errors
- Forgetting
END IF,END CASE, orEND LOOPcauses a compile error. - Omitting
ELSEin a statement-formCASEcan raiseCASE_NOT_FOUNDwhen no branch matches. - Changing a loop variable only on one branch can create an infinite loop.
- Using
=withNULLdoes not test for nullness. UseIS NULLorIS NOT NULL. - An early
RETURNis valid, but verify that every required path returns the declared type.
Exercise
What value does sum_odd_numbers(5) return, and which values does the function add?
Show answer
It returns 9. The function adds 1, 3, and 5, while CONTINUE skips 2 and 4.