PL/pgSQL Cursors and Error Handling
Handling errors and working through results in PL/pgSQL: EXCEPTION blocks, catching errors by name, SQLSTATE and SQLERRM, raising your own errors, GET STACKED DIAGNOSTICS, skipping bad rows, explicit and SQL cursors, and bulk processing with arrays instead of row-by-row loops.
kvi5hnuCode Sprout team member10 min readOn this page
Real procedural code has to cope with things going wrong: a lookup finds nothing, a value won't convert, a row breaks a constraint. It also has to work through results that may be large. This article covers error handling in PL/pgSQL, raising your own errors, cursors for reading results step by step, and the bulk techniques that replace slow row-by-row processing. It builds on the blocks, variables and loops of article 62, and compares Oracle PL/SQL where it differs.
Catching errors with EXCEPTION
Any block can end with an EXCEPTION section. When a statement in the block raises an error, execution jumps to the first handler whose condition matches:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Catching a built-in error by name
CREATE FUNCTION avg_line_value(p_order_id INTEGER)
RETURNS NUMERIC
LANGUAGE plpgsql
AS $$
DECLARE
v_total NUMERIC;
v_lines INTEGER;
BEGIN
SELECT COALESCE(SUM(qty * unit_price), 0), COUNT(*)
INTO v_total, v_lines
FROM order_items WHERE order_id = p_order_id;
RETURN round(v_total / v_lines, 2);
EXCEPTION
WHEN division_by_zero THEN
RETURN NULL; -- an order with no lines has no average
END
$$;
SELECT order_id, avg_line_value(order_id) AS avg_line
FROM (VALUES (101), (103), (999)) AS t(order_id);
-- Raising your own error, with a code and a hint
CREATE FUNCTION check_stock(p_product_id INTEGER, p_qty INTEGER)
RETURNS TEXT
LANGUAGE plpgsql
AS $$
DECLARE
v_stock INTEGER;
BEGIN
SELECT stock INTO STRICT v_stock FROM products WHERE product_id = p_product_id;
IF v_stock < p_qty THEN
RAISE EXCEPTION 'only % in stock for product %', v_stock, p_product_id
USING ERRCODE = 'P0001', HINT = 'Reduce the quantity or back-order the rest.';
END IF;
RETURN 'ok';
END
$$;
SELECT check_stock(3, 5);
SELECT check_stock(3, 500);
SELECT check_stock(99, 1);
order_id | avg_line
----------+----------
101 | 149.00
103 | 51.48
999 | (null)
(3 rows)
check_stock
-------------
ok
(1 row)
psql:/workspace/solution.sql:104: ERROR: only 40 in stock for product 3
HINT: Reduce the quantity or back-order the rest.
CONTEXT: PL/pgSQL function check_stock(integer,integer) line 7 at RAISE
psql:/workspace/solution.sql:105: ERROR: query returned no rows
CONTEXT: PL/pgSQL function check_stock(integer,integer) line 5 at SQL statement
avg_line_value divides an order's total by its number of lines. Order 999 has no lines, so the division fails, and the WHEN division_by_zero handler returns NULL instead. The handler's RETURN ends the function normally, so the caller never sees an error.
Conditions are named after PostgreSQL's error codes. Some common ones:
| Condition | SQLSTATE | Raised by |
|---|---|---|
unique_violation | 23505 | a duplicate key |
foreign_key_violation | 23503 | a missing parent row, or a parent with children |
check_violation | 23514 | a failed CHECK |
not_null_violation | 23502 | NULL in a NOT NULL column |
division_by_zero | 22012 | dividing by zero |
invalid_text_representation | 22P02 | text that won't convert, such as 'abc'::integer |
no_data_found / too_many_rows | P0002 / P0003 | SELECT INTO STRICT |
raise_exception | P0001 | RAISE EXCEPTION with no code given |
OTHERS | any | every error except query cancellation and failed ASSERTs |
A handler can list several conditions with OR, or match a code directly with WHEN SQLSTATE '23505'. Inside a handler, SQLSTATE and SQLERRM hold the error's code and message.
Oracle's PL/SQL works the same way, with its own names: NO_DATA_FOUND, TOO_MANY_ROWS, DUP_VAL_ON_INDEX, ZERO_DIVIDE, OTHERS, and SQLCODE and SQLERRM. T-SQL uses BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH, with ERROR_NUMBER() and ERROR_MESSAGE().
Raising your own errors
RAISE EXCEPTION stops the code with an error, just like a built-in one. In check_stock, ordering 500 head torches fails with a message built from % placeholders, and USING adds details:
ERRCODEsets the SQLSTATE, so callers can catch it by code.P0001is the default for user errors. You can use your own five-character codes, avoiding the classes PostgreSQL uses.HINT,DETAILandMESSAGEadd text that clients show and log.
The third call shows a built-in error passing through: product 99 doesn't exist, so SELECT INTO STRICT raises query returned no rows. There's no handler for it, so the error ends the function and the statement that called it. The CONTEXT line shows where it happened.
RAISE has other levels, DEBUG, LOG, INFO, NOTICE and WARNING, which report a message without stopping. Only EXCEPTION raises an error. ASSERT condition, 'message' raises an error when a condition is false, which is useful for checking assumptions during development.
Raising errors in the database is the right way to enforce rules that constraints can't express, because no application can skip them. Oracle's equivalent is RAISE_APPLICATION_ERROR(-20001, 'message'), and T-SQL's is THROW.
Skipping bad rows: errors and subtransactions
An EXCEPTION section does more than catch the error: it undoes everything the block did before the error, while keeping the work done outside it. That makes it possible to process rows one by one and keep going when some fail:

-- Loading rows one at a time, keeping the good ones and logging the bad
CREATE TABLE staged_products (sku TEXT, name TEXT, price TEXT);
INSERT INTO staged_products VALUES
('TEN-0001', 'Ridge 2 tent', '249.99'),
('TEN-0002', 'Summit 4 tent', 'call us'), -- not a number
('LGT-0001', 'Glow head torch', '34.50'),
('TEN-0001', 'Ridge 2 tent (copy)', '249.99'), -- duplicate SKU
('PCK-0001', 'Trail 30 backpack', '-5'); -- breaks the CHECK
CREATE TABLE catalog (
sku TEXT PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(8, 2) NOT NULL CHECK (price > 0)
);
CREATE TABLE load_errors (sku TEXT, sqlstate TEXT, message TEXT);
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT * FROM staged_products LOOP
BEGIN -- an inner block per row
INSERT INTO catalog VALUES (r.sku, r.name, r.price::numeric);
EXCEPTION
WHEN OTHERS THEN -- undo this row only, record why
INSERT INTO load_errors VALUES (r.sku, SQLSTATE, SQLERRM);
END;
END LOOP;
END
$$;
SELECT * FROM catalog ORDER BY sku;
SELECT * FROM load_errors ORDER BY sqlstate;
sku | name | price
----------+-----------------+--------
LGT-0001 | Glow head torch | 34.50
TEN-0001 | Ridge 2 tent | 249.99
(2 rows)
sku | sqlstate | message
----------+----------+--------------------------------------------------------------------------------
TEN-0002 | 22P02 | invalid input syntax for type numeric: "call us"
TEN-0001 | 23505 | duplicate key value violates unique constraint "catalog_pkey"
PCK-0001 | 23514 | new row for relation "catalog" violates check constraint "catalog_price_check"
(3 rows)
Each row's INSERT runs inside an inner block with its own EXCEPTION section. When a row fails, its handler records the SKU, SQLSTATE and SQLERRM in load_errors, and the loop continues with the next row. Two rows load. Three are rejected with three different errors: a price that isn't a number, a duplicate SKU and a negative price.
Behind the scenes, PostgreSQL implements a block with an EXCEPTION section as a subtransaction, the same mechanism as a savepoint (article 60). Two consequences:
- It costs something. Entering such a block for every row of a million-row load is noticeably slower than a plain loop. Use exception blocks where they're needed, not wrapped around everything.
- Without a handler, an error aborts the whole transaction, including all the rows already processed. That's often what you want: either the whole load succeeds or nothing changes.
For bulk loads, a set-based alternative is often better: validate the staged rows with queries first, for example with pg_input_is_valid(price, 'numeric') (PostgreSQL 16+), anti-joins for duplicates (article 16), and conditions matching the CHECK constraints. Then insert the good rows in one statement and report the rest. PostgreSQL 17's COPY ... ON_ERROR ignore skips rows with conversion errors during file loads.
A common mistake is a WHEN OTHERS handler that hides the error, logging nothing and carrying on. Catch the specific conditions you expect and can handle, and let everything else fail loudly. If you must catch everything, record what happened, or re-raise the error with a bare RAISE; after doing your own clean-up.
The full details of an error
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- GET STACKED DIAGNOSTICS: everything about the error being handled
DO $$
DECLARE
v_state TEXT;
v_message TEXT;
v_detail TEXT;
v_constraint TEXT;
v_table TEXT;
BEGIN
INSERT INTO order_items VALUES (101, 99, 1, 10.00); -- product 99 doesn't exist
EXCEPTION
WHEN foreign_key_violation THEN
GET STACKED DIAGNOSTICS
v_state = RETURNED_SQLSTATE,
v_message = MESSAGE_TEXT,
v_detail = PG_EXCEPTION_DETAIL,
v_constraint = CONSTRAINT_NAME,
v_table = TABLE_NAME;
RAISE NOTICE 'state %, table %, constraint %', v_state, v_table, v_constraint;
RAISE NOTICE '%', v_detail;
END
$$;
psql:/workspace/solution.sql:83: NOTICE: state 23503, table order_items, constraint order_items_product_id_fkey
psql:/workspace/solution.sql:83: NOTICE: Key (product_id)=(99) is not present in table "products".
Inside a handler, GET STACKED DIAGNOSTICS reads more about the error: its SQLSTATE, message, detail and hint, the table, column and constraint involved, and PG_EXCEPTION_CONTEXT, which shows where it happened. Here it reports which constraint failed, order_items_product_id_fkey, and the detail that product 99 doesn't exist. These are the details worth logging when something goes wrong in production.
Cursors
A cursor is a pointer into the result of a query, from which rows can be fetched a few at a time. The FOR r IN query LOOP from article 62 uses a cursor automatically, and is the simplest choice for most loops. Explicit cursors give more control:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- An explicit cursor: open, fetch row by row, close
DO $$
DECLARE
c_big CURSOR FOR
SELECT name, price FROM products WHERE price > 50 ORDER BY price DESC;
v_name products.name%TYPE;
v_price products.price%TYPE;
BEGIN
OPEN c_big;
LOOP
FETCH c_big INTO v_name, v_price;
EXIT WHEN NOT FOUND;
RAISE NOTICE '% at %', v_name, v_price;
END LOOP;
CLOSE c_big;
END
$$;
-- Cursors in plain SQL: read a large result a few rows at a time
BEGIN;
DECLARE product_cur CURSOR FOR SELECT product_id, name FROM products ORDER BY product_id;
FETCH 3 FROM product_cur;
FETCH 3 FROM product_cur;
FETCH 3 FROM product_cur;
CLOSE product_cur;
COMMIT;
psql:/workspace/solution.sql:78: NOTICE: Summit 4 tent at 489.00
psql:/workspace/solution.sql:78: NOTICE: Ridge 2 tent at 249.99
psql:/workspace/solution.sql:78: NOTICE: Trail 30 backpack at 89.95
psql:/workspace/solution.sql:78: NOTICE: Day 18 backpack at 54.00
product_id | name
------------+-----------------
1 | Ridge 2 tent
2 | Summit 4 tent
3 | Glow head torch
(3 rows)
product_id | name
------------+-------------------
4 | Basecamp lantern
5 | Trail 30 backpack
6 | Day 18 backpack
(3 rows)
product_id | name
------------+--------------
7 | Merino socks
(1 row)
In PL/pgSQL:
- Declare the cursor with its query:
c_big CURSOR FOR SELECT .... Cursors can take parameters,CURSOR (p_min NUMERIC) FOR ... WHERE price > p_min. OPENruns the query.FETCH ... INTOreads the next row into variables. When there are no more rows,FOUNDbecomes false, soEXIT WHEN NOT FOUNDends the loop.CLOSEreleases it.
Explicit cursors are useful when rows must be fetched at different points rather than in a single loop, or when a function returns an open cursor, a refcursor, for the caller to fetch from. That's a common way to return results from Oracle procedures (SYS_REFCURSOR), and works in PostgreSQL too.
Cursors also exist in plain SQL. Inside a transaction, DECLARE product_cur CURSOR FOR ... prepares the query, and each FETCH 3 returns the next three rows: 1 to 3, then 4 to 6, then the last one. That's how client programs read results too large to hold in memory at once, and many drivers do it automatically when asked to stream results, such as JDBC with a fetch size or psycopg's server-side cursors. A cursor normally lives until its transaction ends. WITH HOLD keeps it open after commit, at the cost of storing the result. Cursors that page through results for a user interface over several requests are a poor fit: keyset pagination (article 10) works better.
Bulk processing: let SQL do the looping
Row-by-row loops are slow because every statement inside the loop has overhead. Oracle developers deal with this using BULK COLLECT to fetch many rows into a collection at once and FORALL to run a statement for a whole collection. In PostgreSQL, the usual answer is to pass arrays and use one set-based statement:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Bulk work: pass arrays and let one statement handle all the rows
CREATE TABLE price_changes (product_id INTEGER, new_price NUMERIC(8, 2));
CREATE FUNCTION apply_prices(p_ids INTEGER[], p_prices NUMERIC[])
RETURNS INTEGER
LANGUAGE plpgsql
AS $$
DECLARE
v_rows INTEGER;
BEGIN
UPDATE products p
SET price = c.new_price
FROM unnest(p_ids, p_prices) AS c(product_id, new_price) -- arrays side by side as rows
WHERE p.product_id = c.product_id;
GET DIAGNOSTICS v_rows = ROW_COUNT;
RETURN v_rows;
END
$$;
SELECT apply_prices(ARRAY[3, 4, 7], ARRAY[36.00, 28.50, 17.00]) AS rows_updated;
SELECT product_id, name, price FROM products WHERE product_id IN (3, 4, 7) ORDER BY product_id;
-- Collecting many values into one variable with array_agg
DO $$
DECLARE
v_names TEXT[];
BEGIN
SELECT array_agg(name ORDER BY name) INTO v_names FROM products WHERE category = 'packs';
RAISE NOTICE '% packs: %', cardinality(v_names), array_to_string(v_names, ', ');
END
$$;
rows_updated
--------------
3
(1 row)
product_id | name | price
------------+------------------+-------
3 | Glow head torch | 36.00
4 | Basecamp lantern | 28.50
7 | Merino socks | 17.00
(3 rows)
psql:/workspace/solution.sql:93: NOTICE: 2 packs: Day 18 backpack, Trail 30 backpack
apply_pricesreceives two arrays, product IDs and new prices.unnest(p_ids, p_prices)turns them into rows side by side,(3, 36.00),(4, 28.50),(7, 17.00), and a singleUPDATE ... FROMapplies them all. One call, one statement, however many products.GET DIAGNOSTICS v_rows = ROW_COUNTreturns the number of rows the last statement affected.array_agg ... INTOcollects many values into one array variable in a single query, the equivalent ofBULK COLLECT.
The same pattern helps applications: sending 1,000 rows as arrays to one statement, or one multi-row INSERT, is far faster than 1,000 separate round trips. COPY is fastest of all for loading large files.
What's current
- PostgreSQL 17 added
ON_ERROR ignoretoCOPY, which skips rows that fail conversion, withLOG_VERBOSITY verboseto report each one. PostgreSQL 18 addedREJECT_LIMIT, which fails the load once too many rows have been skipped. - PostgreSQL 16 added
pg_input_is_validandpg_input_error_info, which test whether text converts to a type without raising an error. - In SQL Server,
THROW(2012+) is the recommended way to raise errors in new code, rather than the olderRAISERROR.
Common questions
What happens to the work done before an error in a block with an EXCEPTION section? The block's work is undone, as if rolled back to a savepoint at the start of the block. Work done before the block is kept.
Should I catch WHEN OTHERS?
Only to log or clean up, and then usually re-raise with RAISE;. Swallowing every error hides bugs.
Why is my loop with an EXCEPTION block slow? Each entry into the block starts a subtransaction. Move the block outside the loop if you don't need per-row recovery, or validate the data with set-based queries first.
When do I need an explicit cursor?
Rarely. A FOR r IN query LOOP handles most cases. Explicit cursors suit fetching at different points, returning a refcursor, or reading huge results in batches from a client.
How do I do BULK COLLECT and FORALL in PostgreSQL?
Collect values with array_agg ... INTO, and apply arrays with unnest in a single INSERT, UPDATE or DELETE.
Summary
- An
EXCEPTIONsection catches errors by condition name or SQLSTATE.SQLSTATEandSQLERRMdescribe the error. RAISE EXCEPTION ... USING ERRCODE, HINT, DETAILraises your own errors. OtherRAISElevels only report.- A block with an
EXCEPTIONsection is a subtransaction: on error, its work is undone and the code continues after the handler. - Use inner blocks to skip and log bad rows, but prefer set-based validation for large loads.
GET STACKED DIAGNOSTICSreads the full details of an error.- Cursors fetch query results step by step, in PL/pgSQL and in plain SQL.
- Replace row-by-row loops with arrays,
unnestand set-based statements.
Practice questions
Write a function safe_ratio(a NUMERIC, b NUMERIC) that returns a / b, or NULL when b is 0.
Answer
CREATE FUNCTION safe_ratio(a NUMERIC, b NUMERIC)
RETURNS NUMERIC
LANGUAGE plpgsql
AS $$
BEGIN
RETURN a / b;
EXCEPTION
WHEN division_by_zero THEN
RETURN NULL;
END
$$;
Plain SQL does this without an exception block: a / NULLIF(b, 0) (article 8).
A loop inserts 10,000 rows, with no EXCEPTION section, and the 9,000th row breaks a constraint. What's saved?
Answer
Nothing. The error aborts the whole statement, and the transaction, so the 8,999 earlier inserts are undone too.
Write the RAISE statement that stops a function with the message "order 105 is cancelled" (using a variable v_order_id) and the hint "Create a new order instead."
Answer
RAISE EXCEPTION 'order % is cancelled', v_order_id
USING HINT = 'Create a new order instead.';
How would you delete a list of product IDs passed to a function as an INTEGER[] parameter p_ids, in one statement?
Answer
DELETE FROM products WHERE product_id = ANY(p_ids);
Previous: PL/pgSQL Basics: Blocks, Variables and Control Flow

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.