Variables, Control Flow and Errors
Procedural SQL is the part of a database's language that adds variables, IF statements, loops and error handling to plain SQL. Plain SQL describes what data you want; procedural SQL describes steps, one after another. Each database has its own dialect: PL/pgSQL in PostgreSQL, T-SQL in SQL Server, and MySQL's stored program language. It is what you write inside procedures, functions and triggers. In this lesson, we will use PL/pgSQL to declare variables, make decisions, loop over query results, raise and catch errors, and read rows with a cursor, and then compare the same code in T-SQL and MySQL.
In One Minute
DO $$ ... $$runs a one-off PL/pgSQL block without creating a procedure.DECLAREcreates variables;SELECT ... INTO varfills one from a query.IF ... ELSIF ... ELSE ... END IFdecides;FOR row IN query LOOPwalks through results.RAISE NOTICEprints a message;RAISE EXCEPTIONstops with an error.BEGIN ... EXCEPTION WHEN ... THEN ... ENDcatches errors and undoes the block's changes.
Syntax
DO $$
DECLARE
variable_name data_type [:= initial_value];
BEGIN
-- statements
EXCEPTION
WHEN condition THEN
-- handler
END;
$$;| Statement | Does |
|---|---|
var := expression; | Assign a value |
SELECT col INTO var FROM ...; | Store a query result in a variable |
IF ... THEN ... ELSIF ... ELSE ... END IF; | Choose between branches |
FOR r IN SELECT ... LOOP ... END LOOP; | Run once per row |
WHILE condition LOOP ... END LOOP; | Repeat while true |
RAISE NOTICE 'text %', value; | Print a message |
RAISE EXCEPTION 'text %', value; | Stop with an error |
Variables and IF
A one-off check of Advitha's balance, as a DO block:
DO $$
DECLARE
owed NUMERIC;
BEGIN
SELECT sum(c.fee_usd) - COALESCE(sum(p.amount_usd), 0)
INTO owed
FROM enrollments AS e
JOIN courses AS c ON c.course_id = e.course_id
LEFT JOIN payments AS p ON p.student_id = e.student_id AND p.course_id = e.course_id
WHERE e.student_id = 102;
IF owed = 0 THEN
RAISE NOTICE 'Advitha is paid up';
ELSIF owed < 500 THEN
RAISE NOTICE 'Advitha owes a little: % USD', owed;
ELSE
RAISE NOTICE 'Advitha owes % USD; send a reminder', owed;
END IF;
END;
$$;NOTICE: Advitha owes 850.00 USD; send a reminder
DOExplanation: DECLARE creates owed, and SELECT ... INTO owed stores the query's single result in it. Advitha owes 850.00 across her two courses, so the ELSE branch runs. RAISE NOTICE prints a message, shown as a NOTICE line above the command tag, just as psql shows it.
Loops
FOR r IN query LOOP runs its body once for each row, with r holding the current row:
DO $$
DECLARE
r RECORD;
total NUMERIC := 0;
BEGIN
FOR r IN
SELECT s.first_name, sum(p.amount_usd) AS paid
FROM students AS s
JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.first_name
ORDER BY s.first_name
LOOP
total := total + r.paid;
RAISE NOTICE '% paid %, running total %', r.first_name, r.paid, total;
END LOOP;
END;
$$;NOTICE: Navika paid 450.00, running total 450.00
NOTICE: Srihitha paid 1700.00, running total 2150.00
DOExplanation: The query returns two rows (Advitha has no payments, so the inner join leaves her out), and the loop runs twice, adding to total each time. RECORD is a variable that takes the shape of whatever row it's given.
WHILE repeats while a condition is true, and FOR i IN 1..3 LOOP counts. EXIT leaves a loop early and CONTINUE skips to the next pass.
Raising and Catching Errors
An EXCEPTION section catches errors raised inside its block. Crucially, PostgreSQL first undoes every change the block made, as if it had a savepoint at BEGIN:
DO $$
BEGIN
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, 150.00, '2026-01-05', '2026-01-05', 'card');
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, -5.00, '2026-01-05', '2026-01-05', 'card');
EXCEPTION
WHEN check_violation THEN
RAISE NOTICE 'caught: %', SQLERRM;
END;
$$;
SELECT count(*) AS payments FROM payments;NOTICE: caught: new row for relation "payments" violates check constraint "payments_amount_usd_check"
DO
payments
----------
7
(1 row)Explanation: The second insert breaks the amount_usd > 0 check. The handler for check_violation catches it and prints SQLERRM, the error message. The block finishes without an error, but the first insert was undone as well: there are still 7 payments. Conditions have names such as unique_violation, foreign_key_violation, division_by_zero and others (any error).
Your own errors can carry a code and a hint, which programs can check:
DO $$
BEGIN
RAISE EXCEPTION 'fee must be positive, got %', -5
USING ERRCODE = 'check_violation', HINT = 'Use an amount greater than 0.';
END;
$$;ERROR: fee must be positive, got -5
HINT: Use an amount greater than 0.Cursors (Legacy)
A cursor reads a query's result a few rows at a time. FOR ... LOOP uses one behind the scenes, so explicit cursors are rarely needed now; you'll meet them in older code and in SQL Server scripts. In plain SQL, a cursor lives inside a transaction:
BEGIN;
DECLARE pay_cursor CURSOR FOR
SELECT payment_id, amount_usd FROM payments ORDER BY payment_id;
FETCH 2 FROM pay_cursor;
FETCH 2 FROM pay_cursor;
CLOSE pay_cursor;
COMMIT;BEGIN
DECLARE CURSOR
payment_id | amount_usd
------------+------------
1 | 450.00
2 | 250.00
(2 rows)
payment_id | amount_usd
------------+------------
3 | 250.00
4 | 550.00
(2 rows)
CLOSE CURSOR
COMMITExplanation: Each FETCH 2 returns the next two rows, continuing where the last one stopped. Programs use this to process huge results without loading them all into memory at once.
The Same Logic in Three Dialects
Here is the balance check from earlier, as PostgreSQL, SQL Server and MySQL each write it:
-- PostgreSQL (PL/pgSQL)
DO $$
DECLARE owed NUMERIC;
BEGIN
SELECT 850.00 INTO owed;
IF owed > 500 THEN RAISE NOTICE 'owes %', owed; END IF;
EXCEPTION WHEN others THEN RAISE NOTICE 'failed: %', SQLERRM;
END $$;-- SQL Server (T-SQL)
DECLARE @owed DECIMAL(8,2);
BEGIN TRY
SELECT @owed = 850.00;
IF @owed > 500 PRINT CONCAT('owes ', @owed);
END TRY
BEGIN CATCH
PRINT CONCAT('failed: ', ERROR_MESSAGE());
END CATCH;-- MySQL (inside a stored procedure)
DECLARE owed DECIMAL(8,2);
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'failed' AS message;
SELECT 850.00 INTO owed;
IF owed > 500 THEN SELECT CONCAT('owes ', owed) AS message; END IF;| Feature | PostgreSQL | SQL Server | MySQL |
|---|---|---|---|
| Variable | owed NUMERIC; in DECLARE | DECLARE @owed DECIMAL(8,2); | DECLARE owed DECIMAL(8,2); |
| Assign | owed := 1; or SELECT ... INTO owed | SET @owed = 1; or SELECT @owed = ... | SET owed = 1; or SELECT ... INTO owed |
RAISE NOTICE | PRINT | SELECT a message | |
| Raise error | RAISE EXCEPTION | THROW (or RAISERROR) | SIGNAL SQLSTATE '45000' |
| Catch | EXCEPTION WHEN ... THEN | BEGIN TRY ... BEGIN CATCH | DECLARE ... HANDLER FOR |
| One-off block | DO $$ ... $$ | Any batch | Only inside stored programs |
Tabs showing each database's version are coming to this course.
Common Mistakes
Looping where one SQL statement would do. Row-by-row code is slow; think in sets first.
SELECT INTO returning several rows. PL/pgSQL keeps the first row silently; add STRICT (SELECT ... INTO STRICT v) to raise an error instead.
Catching others and ignoring it. Errors vanish and data goes wrong quietly.
Forgetting that a caught error undoes the block's changes. Work done before the error inside the same block is rolled back.
Interview Corner
What is PL/pgSQL?
PostgreSQL's procedural language, which adds variables, conditions, loops and error handling to SQL, used in functions, procedures, triggers and DO blocks. SQL Server's equivalent is T-SQL; Oracle's is PL/SQL.
How do you handle errors in PL/pgSQL?
With an EXCEPTION section: BEGIN ... EXCEPTION WHEN condition THEN ... END. The block's changes are rolled back before the handler runs. SQL Server uses TRY ... CATCH.
What is a cursor, and why are cursors discouraged?
A cursor steps through a query's rows one at a time. Row-by-row processing is usually much slower than one set-based statement, so cursors are a last resort.
Practice
Challenge: Write a DO block that loops over the courses ordered by course_id and prints each title with a label: 'premium' if its fee is 500.00 or more, otherwise 'standard'.
Show solution
DO $$
DECLARE
r RECORD;
label TEXT;
BEGIN
FOR r IN SELECT title, fee_usd FROM courses ORDER BY course_id LOOP
IF r.fee_usd >= 500 THEN
label := 'premium';
ELSE
label := 'standard';
END IF;
RAISE NOTICE '%: % (%)', r.title, label, r.fee_usd;
END LOOP;
END;
$$;NOTICE: Java Basics: standard (450.00)
NOTICE: Java OOP: premium (500.00)
NOTICE: Java Collections: premium (550.00)
NOTICE: SQL Basics: standard (400.00)
NOTICE: JavaScript Basics: standard (450.00)
NOTICE: Git Basics: standard (250.00)
DOTwo courses are premium. As a single query, this is SELECT title, CASE WHEN fee_usd >= 500 THEN 'premium' ELSE 'standard' END FROM courses, which shows why set-based SQL is usually the better choice.
Key Takeaways
| You want to | Write |
|---|---|
| Run a one-off block | DO $$ BEGIN ... END $$; |
| Store a query result | SELECT col INTO var FROM ...; |
| Loop over rows | FOR r IN SELECT ... LOOP ... END LOOP; |
| Print / stop | RAISE NOTICE '...'; / RAISE EXCEPTION '...'; |
| Catch an error | EXCEPTION WHEN unique_violation THEN ... |
Was this tutorial helpful?