PL/pgSQL blocks and SQL statements
Overview
PL/pgSQL is PostgreSQL’s procedural language, not portable standard SQL. A block has optional DECLARE variables, BEGIN statements, optional EXCEPTION handlers and END. BEGIN inside a procedural block does not begin a SQL transaction. SQL expressions and DML remain available inside the block.
First example
SELECT COALESCE(SUM(qty),0) FROM pc_item;Observed SQLite result (rows in JSON):
[ [ 14 ]]How it works
Use SELECT ... INTO variable in PL/pgSQL for a single-row result, not the SQL command that creates a table. INTO STRICT requires exactly one row; without STRICT the first row is used (choose a deterministic order if needed), or NULLs are assigned if none exists. PERFORM evaluates a query whose result is intentionally discarded; FOUND is a local status flag affected by certain statements. The examples compute a quantity total and a conditional status using ordinary SQLite SQL; the native DO block uses a typed variable and asserts an expected invariant. DO is an anonymous one-time block, not a persistent procedure, and does not return a query result set. T-SQL and PL/SQL have different syntax and runtime behavior.
Practical example
SELECT id,CASE WHEN qty=0 THEN 'empty' ELSE 'available' END FROM pc_item ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "available" ], [ 2, "available" ], [ 3, "empty" ]]Practice and mistakes
Practice: change the total query to include only quantity greater than zero. Hint 1: filter before SUM. Hint 2: use COALESCE for an empty input. Explain why BEGIN in DO does not start a transaction.
PostgreSQL 17 example — NOT RUN
BEGIN;DO $$DECLARE total bigint;BEGIN SELECT COALESCE(SUM(qty),0) INTO total FROM pc_item; IF total <> 14 THEN RAISE EXCEPTION 'unexpected total'; END IF;END;$$;SELECT SUM(qty) FROM pc_item;ROLLBACK;Expected result, not executed: [[14]]