Introduction
The CASE statement helps you choose different actions based on conditions inside your PL/pgSQL code. It works like a simple decision maker.
Jump into concepts and practice - no test required
The CASE statement helps you choose different actions based on conditions inside your PL/pgSQL code. It works like a simple decision maker.
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default_result END CASE;
The CASE statement checks each WHEN condition in order.
If none of the WHEN conditions match, the ELSE part runs (optional).
CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'F' END CASE;
CASE day_of_week WHEN 'Monday' THEN 'Start of week' WHEN 'Friday' THEN 'End of workweek' ELSE 'Midweek' END CASE;
This code block sets a score, uses CASE to find the grade, and prints the result.
DO $$ DECLARE score INTEGER := 85; grade TEXT; BEGIN grade := CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'F' END CASE; RAISE NOTICE 'Score: %, Grade: %', score, grade; END $$;
CASE in PL/pgSQL must end with END CASE; inside procedural blocks.
You can use CASE to assign values or control flow inside functions and DO blocks.
CASE helps you choose actions based on conditions.
It is cleaner than many IF-ELSE statements.
Use END CASE; to close the CASE block in PL/pgSQL.
CASE in PL/pgSQL?END CASE; to mark its end clearly.END; ends blocks like functions, but CASE specifically needs END CASE;. FINISH CASE; and STOP; are invalid keywords.DECLARE
grade CHAR := 'B';
result TEXT;
BEGIN
CASE grade
WHEN 'A' THEN result := 'Excellent';
WHEN 'B' THEN result := 'Good';
ELSE result := 'Average';
END CASE;
RETURN result;
END;grade is set to 'B'.result becomes 'Good'.DECLARE
score INT := 85;
grade TEXT;
BEGIN
CASE
WHEN score >= 90 THEN grade := 'A';
WHEN score >= 80 THEN grade := 'B';
ELSE grade := 'C';
END;
RETURN grade;
END;END; but PL/pgSQL requires END CASE; to close CASE.WHEN score IS NULL to check NULL values.CASE WHEN score IS NULL THEN RETURN 'Invalid'; WHEN score >= 50 THEN RETURN 'Pass'; ELSE RETURN 'Fail'; END CASE;.