PL/pgSQL Basics: Blocks, Variables and Control Flow
An introduction to procedural code inside the database with PL/pgSQL: anonymous DO blocks, functions, declaring variables with %TYPE and %ROWTYPE, SELECT INTO, IF and CASE, loops over ranges, queries and arrays, RAISE NOTICE, and how Oracle PL/SQL and T-SQL compare.
kvi5hnuCode Sprout team member9 min readOn this page
SQL describes what result you want, and the database works out how to produce it. Sometimes you need to say how, step by step: look something up, decide what to do based on it, repeat for each row, and handle errors along the way. Every major database includes a procedural language for that, which runs inside the database server, next to the data:
| Database | Procedural language |
|---|---|
| PostgreSQL | PL/pgSQL (also PL/Python, PL/Perl and others as extensions) |
| Oracle | PL/SQL |
| SQL Server | T-SQL (Transact-SQL) |
| MySQL | stored program syntax from the SQL/PSM standard |
| Db2 | SQL PL |
This part of the course uses PL/pgSQL, which was modelled closely on Oracle's PL/SQL, so most of what you learn transfers directly. This article covers the building blocks: blocks, variables, assignments, conditions and loops. Articles 63 to 66 cover cursors and error handling, functions and procedures, triggers, and dynamic SQL.
A word of caution before starting: prefer plain SQL when it can do the job. A single UPDATE with a CASE expression is faster, shorter and easier to read than a loop that updates rows one at a time. Procedural code earns its place for logic that genuinely needs steps, decisions and error handling.
Blocks
PL/pgSQL code is organised in blocks:

- An optional
DECLAREsection declares variables. BEGIN...ENDcontains the statements, each ending with a semicolon.- An optional
EXCEPTIONsection handles errors (article 63).
The body of a function is a string, usually written between dollar quotes, $$ ... $$, so quotes inside it don't need escaping. Blocks can be nested, and a nested block can have its own declarations and exception handlers.
The quickest way to run procedural code is an anonymous block with DO, which runs once and isn't stored:
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 anonymous block: declare variables, query into them, branch, and report
DO $$
DECLARE
v_name customers.name%TYPE; -- same type as the column
v_orders INTEGER;
v_label TEXT;
BEGIN
SELECT c.name, COUNT(o.order_id)
INTO v_name, v_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id = 1
GROUP BY c.name;
IF v_orders >= 2 THEN
v_label := 'regular';
ELSIF v_orders = 1 THEN
v_label := 'new';
ELSE
v_label := 'prospect';
END IF;
RAISE NOTICE '% has % orders: %', v_name, v_orders, v_label;
END
$$;
psql:/workspace/solution.sql:86: NOTICE: Asha Rao has 2 orders: regular
This block:
- declares
v_namewithcustomers.name%TYPE, meaning "whatever type thenamecolumn has", so the code keeps working if the column's type changes - runs a query and stores its result in variables with
SELECT ... INTO - chooses a label with
IF ... ELSIF ... ELSE ... END IF - reports the result with
RAISE NOTICE, where each%is replaced by the next argument
RAISE NOTICE sends a message to the client, which psql prints with the script line it came from. It's the PL/pgSQL equivalent of Oracle's DBMS_OUTPUT.PUT_LINE and T-SQL's PRINT, and is handy for learning and debugging. A DO block can't return a result set, so real code usually lives in functions.
Variables and assignment
Variables are declared in the DECLARE section, with a name, a type and an optional initial value:
DECLARE
v_count INTEGER := 0;
v_rate CONSTANT NUMERIC := 0.05; -- can't be changed
v_city TEXT NOT NULL := 'Pune'; -- can't be set to NULL
v_name customers.name%TYPE; -- the column's type
v_product products%ROWTYPE; -- a whole row of the table
r RECORD; -- a row of any shape
- A variable without an initial value starts as NULL.
:=assigns a value:v_count := v_count + 1;.=also works for assignment in PL/pgSQL, but:=makes the intent clear and matches PL/SQL.%TYPEand%ROWTYPEtie variables to the schema. A%ROWTYPEvariable has a field for every column, accessed asv_product.price.RECORDtakes the shape of whatever row is assigned to it, which suits loops over queries.
A common convention, used here, prefixes variables with v_ and parameters with p_. It isn't required, but it prevents a subtle bug: if a variable has the same name as a column, a query that mentions that name is ambiguous, and PL/pgSQL raises an error rather than guessing.
Getting data with SELECT INTO
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);
-- SELECT INTO that finds nothing: variables become NULL and FOUND is false
DO $$
DECLARE
v_name customers.name%TYPE;
BEGIN
SELECT name INTO v_name FROM customers WHERE customer_id = 99;
IF NOT FOUND THEN
RAISE NOTICE 'no customer 99 (v_name is %)', COALESCE(v_name, 'NULL');
END IF;
END
$$;
-- INTO STRICT insists on exactly one row, and raises an error otherwise
DO $$
DECLARE
v_name customers.name%TYPE;
BEGIN
SELECT name INTO STRICT v_name FROM customers WHERE city = 'Pune';
END
$$;
-- A %ROWTYPE variable holds a whole row
DO $$
DECLARE
v_product products%ROWTYPE;
BEGIN
SELECT * INTO v_product FROM products WHERE product_id = 2;
RAISE NOTICE '% costs % and weighs % g', v_product.name, v_product.price, v_product.weight_g;
END
$$;
psql:/workspace/solution.sql:72: NOTICE: no customer 99 (v_name is NULL)
psql:/workspace/solution.sql:81: ERROR: query returned more than one row
HINT: Make sure the query returns a single row, or use LIMIT 1.
CONTEXT: PL/pgSQL function inline_code_block line 5 at SQL statement
psql:/workspace/solution.sql:91: NOTICE: Summit 4 tent costs 489.00 and weighs 4300 g
SELECT ... INTO behaves in ways that surprise people coming from Oracle:
- If the query returns no rows, the variables are set to NULL and there's no error. The special variable
FOUNDbecomes false, so check it. - If it returns several rows, the first one is used, silently.
INTO STRICTdemands exactly one row and raises an error otherwise:query returned more than one rowhere, because two customers live in Pune, orquery returned no rows. That's how Oracle'sSELECT INTOalways behaves, raisingNO_DATA_FOUNDorTOO_MANY_ROWS.
FOUND is also set by UPDATE, INSERT and DELETE (true if at least one row was affected) and by loops. GET DIAGNOSTICS v_rows = ROW_COUNT gives the exact number of rows the last statement affected.
Statements that don't return rows, such as UPDATE, run as they are. A query whose result you want to discard uses PERFORM instead of SELECT, for example PERFORM pg_notify('orders', 'new').
Conditions
PL/pgSQL has two conditional statements:
IF v_stock = 0 THEN
v_status := 'out of stock';
ELSIF v_stock < 10 THEN
v_status := 'low';
ELSE
v_status := 'ok';
END IF;
CASE v_category
WHEN 'tents', 'packs' THEN v_shipping := 9.99;
WHEN 'clothing' THEN v_shipping := 2.99;
ELSE v_shipping := 4.99;
END CASE;
Note the spelling: ELSIF, as in PL/SQL, not ELSEIF or ELSE IF. PL/pgSQL also accepts ELSEIF. The CASE statement also has a searched form, CASE WHEN condition THEN .... Unlike the CASE expression in SQL (article 11), a CASE statement with no matching branch and no ELSE raises an error, case not found, instead of returning NULL.
Conditions follow SQL's three-valued logic: if v_stock is NULL, v_stock = 0 is unknown, so the IF branch is skipped and execution falls through to ELSE. Test for NULL explicitly with IS NULL when it matters (article 8).
Loops
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);
-- A function with a loop: compound growth of a price, year by year
CREATE FUNCTION price_after(p_price NUMERIC, p_rate NUMERIC, p_years INTEGER)
RETURNS NUMERIC
LANGUAGE plpgsql
AS $$
DECLARE
v_price NUMERIC := p_price;
BEGIN
FOR i IN 1 .. p_years LOOP
v_price := round(v_price * (1 + p_rate), 2);
END LOOP;
RETURN v_price;
END
$$;
SELECT name, price,
price_after(price, 0.05, 3) AS in_three_years
FROM products
WHERE category = 'tents'
ORDER BY product_id;
-- WHILE and EXIT: how many years until the price doubles?
DO $$
DECLARE
v_price NUMERIC := 100;
v_years INTEGER := 0;
BEGIN
WHILE v_price < 200 LOOP
v_price := v_price * 1.07;
v_years := v_years + 1;
END LOOP;
RAISE NOTICE 'At 7%% a year, prices double in % years', v_years;
END
$$;
name | price | in_three_years
---------------+--------+----------------
Ridge 2 tent | 249.99 | 289.39
Summit 4 tent | 489.00 | 566.08
(2 rows)
psql:/workspace/solution.sql:95: NOTICE: At 7% a year, prices double in 11 years
The function price_after applies a yearly increase with an integer FOR loop: FOR i IN 1 .. p_years LOOP. The loop variable i is declared automatically. REVERSE counts down, and BY 2 changes the step. The WHILE loop repeats while its condition is true, here until a price doubles. (In RAISE, %% prints a literal percent sign.)
The basic LOOP repeats forever, until an EXIT:
LOOP
v_n := v_n + 1;
EXIT WHEN v_n >= 10; -- leave the loop
CONTINUE WHEN v_n % 2 = 0; -- skip to the next iteration
-- ...
END LOOP;
Loops can be labelled, <<outer>>, so that EXIT outer leaves an outer loop from inside an inner one.
The most useful loops go through query results and arrays:
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);
-- Looping over query results and arrays
CREATE FUNCTION category_report()
RETURNS TABLE (category TEXT, line TEXT)
LANGUAGE plpgsql
AS $$
DECLARE
r RECORD;
BEGIN
FOR r IN
SELECT p.category, COUNT(*) AS n, MAX(p.price) AS top_price
FROM products p
GROUP BY p.category
ORDER BY p.category
LOOP
category := r.category;
line := r.n || ' product(s), most expensive ' || r.top_price;
RETURN NEXT; -- add this row to the result
END LOOP;
END
$$;
SELECT * FROM category_report();
-- FOREACH walks through an array
DO $$
DECLARE
v_city TEXT;
v_n INTEGER;
BEGIN
FOREACH v_city IN ARRAY ARRAY['Pune', 'Bath', 'Leeds', 'York'] LOOP
SELECT COUNT(*) INTO v_n FROM customers WHERE city = v_city;
CONTINUE WHEN v_n = 0; -- skip cities with no customers
RAISE NOTICE '%: % customer(s)', v_city, v_n;
END LOOP;
END
$$;
category | line
----------+-------------------------------------
clothing | 1 product(s), most expensive 16.00
lighting | 2 product(s), most expensive 34.50
packs | 2 product(s), most expensive 89.95
tents | 2 product(s), most expensive 489.00
(4 rows)
psql:/workspace/solution.sql:97: NOTICE: Pune: 2 customer(s)
psql:/workspace/solution.sql:97: NOTICE: Leeds: 2 customer(s)
psql:/workspace/solution.sql:97: NOTICE: York: 1 customer(s)
FOR r IN query LOOPruns the query and puts each row in turn into theRECORDvariabler. PL/pgSQL fetches the rows in batches behind the scenes, so this works on large results without loading them all into memory.- The function returns a table:
RETURNS TABLE (category TEXT, line TEXT)declares the output columns, which act as variables. EachRETURN NEXTadds the current values as a row. Article 64 covers set-returning functions in more depth. FOREACH v_city IN ARRAY ...walks through an array.CONTINUE WHENskips Bath, which has no customers.
This report is a good example of when not to loop in real code: a single SELECT ... GROUP BY produces the same rows faster. Loops over queries are worth it when each row needs procedural work, such as calling another function, handling errors row by row, or deciding between different actions.
PL/pgSQL, PL/SQL and T-SQL side by side
| PL/pgSQL | Oracle PL/SQL | SQL Server T-SQL | |
|---|---|---|---|
| anonymous block | DO $$ ... $$; | DECLARE ... BEGIN ... END; then / | statements in a batch |
| variable | v_n INTEGER := 0; in DECLARE | the same | DECLARE @n INT = 0; |
| assign | v_n := 1; | v_n := 1; | SET @n = 1; |
| query into variables | SELECT x INTO v_x FROM ... | the same, with errors on 0 or many rows | SELECT @x = x FROM ... |
RAISE NOTICE '%', v; | DBMS_OUTPUT.PUT_LINE(v); | PRINT @v; | |
| else-if | ELSIF | ELSIF | ELSE IF |
| loops | LOOP, WHILE, FOR, FOREACH | LOOP, WHILE, FOR | WHILE only |
T-SQL is the most different: variables start with @, there are no %TYPE declarations, and WHILE is the only loop. MySQL has no anonymous blocks: DECLARE, IF and loops work only inside stored procedures, functions and triggers, created with a changed DELIMITER in the mysql client.
What's current
- PostgreSQL 17 allows
%TYPEand%ROWTYPEto be followed by[], declaring an array of the column's or row's type, such asv_names customers.name%TYPE[]. The core language has been stable for many releases. - PostgreSQL 14 added
OUTparameters to procedures, and PostgreSQL 11 added procedures with transaction control (article 64). - Oracle 23ai and 26ai added a SQL
BOOLEANtype, which PL/SQL had long supported internally, so boolean values can now pass between SQL and PL/SQL.
Common questions
Why doesn't my DO block show any results?
A DO block can't return rows. Use RAISE NOTICE for messages, or write a function and SELECT from it.
What happens if SELECT INTO finds no row?
In PL/pgSQL, the variables become NULL and FOUND is false, with no error. Add STRICT to make it an error, as in Oracle.
Should I use a loop to update rows one at a time?
Usually not. One set-based UPDATE is much faster. Loop only when each row needs separate procedural handling.
Why does PL/pgSQL complain that a column reference is ambiguous?
A variable or parameter has the same name as a column used in a query. Rename the variable, for example with a v_ or p_ prefix, or qualify the column with its table.
Is it ELSIF or ELSEIF?
ELSIF in PL/pgSQL and PL/SQL. PL/pgSQL also accepts ELSEIF.
Summary
- Procedural languages such as PL/pgSQL, PL/SQL and T-SQL run step-by-step logic inside the database.
- Code is organised in blocks:
DECLARE,BEGIN ... END, and an optionalEXCEPTIONsection. DOruns an anonymous block once. Functions store code and can return values and tables.- Declare variables with types,
%TYPE,%ROWTYPEorRECORD, and assign with:=. SELECT INTOdoesn't fail on zero or many rows unlessSTRICTis used. CheckFOUND.IF ... ELSIF ... END IFandCASEmake decisions.LOOP,WHILE,FORandFOREACHrepeat.FOR r IN query LOOPprocesses query rows one at a time. Prefer set-based SQL when it can do the same job.
Practice questions
Write a DO block that counts the products with stock below 20 and prints "n products need restocking".
Answer
DO $$
DECLARE
v_n INTEGER;
BEGIN
SELECT COUNT(*) INTO v_n FROM products WHERE stock < 20;
RAISE NOTICE '% products need restocking', v_n;
END
$$;
In PL/pgSQL, SELECT name INTO v_name FROM customers WHERE customer_id = 99 finds no row. What's in v_name, and how can the code tell?
Answer
v_name is NULL, and FOUND is false. With INTO STRICT, the statement would raise a "query returned no rows" error instead.
Write a function factorial(n INTEGER) that returns n! as a NUMERIC, using a FOR loop.
Answer
CREATE FUNCTION factorial(n INTEGER)
RETURNS NUMERIC
LANGUAGE plpgsql
AS $$
DECLARE
v_result NUMERIC := 1;
BEGIN
FOR i IN 2 .. n LOOP
v_result := v_result * i;
END LOOP;
RETURN v_result;
END
$$;
SELECT factorial(5); -- 120
For n of 0 or 1, the loop doesn't run, and the function returns 1.
A colleague wrote a loop that reads every product and runs an UPDATE for each one to raise prices by 5%. What would you suggest?
Answer
A single set-based statement: UPDATE products SET price = round(price * 1.05, 2);. It does the same work in one statement, much faster, and is easier to read.
Previous: Isolation Levels, Locking and MVCC

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.