Variables, Control Flow and Errors

Updated · 10 min read
hardPostgreSQL 18sqlplpgsqlt-sqlvariablesloopsexceptionscursorsinterview

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.
  • DECLARE creates variables; SELECT ... INTO var fills one from a query.
  • IF ... ELSIF ... ELSE ... END IF decides; FOR row IN query LOOP walks through results.
  • RAISE NOTICE prints a message; RAISE EXCEPTION stops with an error.
  • BEGIN ... EXCEPTION WHEN ... THEN ... END catches errors and undoes the block's changes.

Syntax

SQL
DO $$
DECLARE
  variable_name data_type [:= initial_value];
BEGIN
  -- statements
EXCEPTION
  WHEN condition THEN
    -- handler
END;
$$;
StatementDoes
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:

SQL▶ Try it
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;
$$;
Output
NOTICE:  Advitha owes 850.00 USD; send a reminder
DO

Explanation: 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:

SQL▶ Try it
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;
$$;
Output
NOTICE:  Navika paid 450.00, running total 450.00
NOTICE:  Srihitha paid 1700.00, running total 2150.00
DO

Explanation: 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.

Each row of the query becomes r for one pass of the loop; total grows 450.00 then 2150.00

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:

SQL▶ Try it
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;
Output
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).

An error inside the block rolls back everything the block did, then the handler runs

Your own errors can carry a code and a hint, which programs can check:

SQL▶ Try it
DO $$
BEGIN
  RAISE EXCEPTION 'fee must be positive, got %', -5
    USING ERRCODE = 'check_violation', HINT = 'Use an amount greater than 0.';
END;
$$;
Output
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:

SQL▶ Try it
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;
Output
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
 
COMMIT

Explanation: 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:

SQL
-- 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
-- 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;
SQL
-- 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;
FeaturePostgreSQLSQL ServerMySQL
Variableowed NUMERIC; in DECLAREDECLARE @owed DECIMAL(8,2);DECLARE owed DECIMAL(8,2);
Assignowed := 1; or SELECT ... INTO owedSET @owed = 1; or SELECT @owed = ...SET owed = 1; or SELECT ... INTO owed
PrintRAISE NOTICEPRINTSELECT a message
Raise errorRAISE EXCEPTIONTHROW (or RAISERROR)SIGNAL SQLSTATE '45000'
CatchEXCEPTION WHEN ... THENBEGIN TRY ... BEGIN CATCHDECLARE ... HANDLER FOR
One-off blockDO $$ ... $$Any batchOnly inside stored programs

Tabs showing each database's version are coming to this course.

Variables, printing, raising and catching errors in PL/pgSQL, T-SQL and MySQL

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
SQL▶ Try it
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;
$$;
Output
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)
DO

Two 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.

Quick check: Procedural SQL

3 questions
1What does SELECT ... INTO owed do in PL/pgSQL?
2An error is caught by an EXCEPTION section. What happens to the block's earlier changes?
3What is SQL Server's equivalent of RAISE EXCEPTION?

Key Takeaways

You want toWrite
Run a one-off blockDO $$ BEGIN ... END $$;
Store a query resultSELECT col INTO var FROM ...;
Loop over rowsFOR r IN SELECT ... LOOP ... END LOOP;
Print / stopRAISE NOTICE '...'; / RAISE EXCEPTION '...';
Catch an errorEXCEPTION WHEN unique_violation THEN ...

Was this tutorial helpful?

Lesson 87 of 115