Variables, conditions and loops
Overview
Procedural SQL stores intermediate values in typed variables and chooses actions using IF/ELSIF/ELSE or CASE. PL/pgSQL supports LOOP, WHILE, integer FOR and query-result FOR loops. Use EXIT to leave a loop and CONTINUE to skip an iteration. Prefer one set-based SQL statement when all rows follow the same rule.
First example
SELECT id,CASE WHEN qty<6 THEN 6-qty ELSE 0 END AS deficit FROM pc_item ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 0 ], [ 2, 2 ], [ 3, 6 ]]How it works
The first query computes the deficit below a target of six units. The second updates all deficient rows to six, then reads the result before rollback. The native block iterates over ordered item records and applies the same rule; it is useful for understanding control flow, not a performance recommendation. In PL/pgSQL assignment uses := (or =); %TYPE and %ROWTYPE can align variable types with schema objects. Avoid a variable name matching a column; qualify columns with aliases. SQL CASE is an expression, whereas procedural IF controls statements. NULL conditions are not true, so define a NULL policy explicitly. A loop should have a bounded or clearly terminating condition.
Practical example
BEGIN;UPDATE pc_item SET qty=6 WHERE qty<6;SELECT id,qty FROM pc_item ORDER BY id;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 1, 10 ], [ 2, 6 ], [ 3, 6 ]]Practice and mistakes
Practice: use target eight instead of six and predict each new quantity. Hint 1: keep items above the threshold unchanged. Hint 2: WHERE qty<8. Expected 10,8,8. Roll back and compare with the procedural version.
PostgreSQL 17 example — NOT RUN
BEGIN;DO $$DECLARE r record;BEGIN FOR r IN SELECT id,qty FROM pc_item ORDER BY id LOOP IF r.qty < 6 THEN UPDATE pc_item SET qty=6 WHERE id=r.id; END IF; END LOOP;END;$$;SELECT id,qty FROM pc_item ORDER BY id;ROLLBACK;Expected result, not executed: [[1, 10], [2, 6], [3, 6]]