Sub topic 8
Looping over query results and using cursors
This chapter shows how a PL/pgSQL function processes a query result one row at a time. It covers the FOR loop over a query, RETURN NEXT, and explicit cursors. It assumes you can already declare variables, use IF and LOOP, run SELECT INTO, check FOUND, and write a function with RETURNS TABLE.
Why loop over rows at all
SQL works on sets of rows, so most work needs no loop. A loop makes sense when each row needs procedural treatment. Examples are calling another routine per row, building a value that depends on the previous row, or raising a notice for specific rows. If you only need an aggregate or a join, write plain SQL, because it is almost always faster.
The FOR loop over a query
The simplest form is FOR target IN query LOOP ... END LOOP. PL/pgSQL runs the query and assigns each row to the target in turn. The target is usually a record variable, a %ROWTYPE variable, or a list of scalar variables.
CREATE FUNCTION total_for_customer(p_customer_id integer)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r record;
v_sum numeric := 0;
BEGIN
FOR r IN
SELECT o.total FROM orders o WHERE o.customer_id = p_customer_id
LOOP
v_sum := v_sum + r.total;
END LOOP;
RETURN v_sum;
END;
$$;This function works, but SELECT coalesce(sum(total), 0) FROM orders WHERE customer_id = ... does the same job in one statement. The loop version is useful as a pattern, not as a recommendation.
You can also skip the DECLARE entry for the loop variable. If you write FOR r IN SELECT ... and r is not declared, PL/pgSQL creates it automatically. It exists only inside the loop.
What happens inside the loop
- Each row is read through an internal cursor. PL/pgSQL fetches rows in batches, so a large result does not have to fit in memory at once.
- The query sees a snapshot taken when the loop starts. Rows you insert, update, or delete from inside the loop do not change which rows the loop visits.
- After the loop ends,
FOUNDis true if the loop ran at least once, and false if the query returned no rows. - A
recordvariable you declared yourself keeps the last row after the loop. An automatically created loop variable is gone.
Controlling the loop
EXIT leaves the loop and CONTINUE jumps to the next row. Both accept a WHEN condition. For nested loops, add a label before the loop and name it in EXIT or CONTINUE.
CREATE FUNCTION flag_large_orders(p_limit numeric)
RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
c record;
o record;
v_flagged integer := 0;
BEGIN
<<per_customer>>
FOR c IN SELECT id FROM customers ORDER BY id LOOP
FOR o IN SELECT id, total FROM orders WHERE customer_id = c.id ORDER BY id LOOP
CONTINUE WHEN o.total <= p_limit;
RAISE NOTICE 'customer % has large order % (%)', c.id, o.id, o.total;
v_flagged := v_flagged + 1;
CONTINUE per_customer;
END LOOP;
END LOOP;
RETURN v_flagged;
END;
$$;The function reports at most one large order per customer. CONTINUE per_customer abandons the inner loop and moves to the next customer.
Building a result set with RETURN NEXT
In a function that returns a set, RETURN NEXT adds the current output values to the result and keeps running. With RETURNS TABLE, the output columns behave like variables, so you assign them and then call RETURN NEXT.
CREATE FUNCTION order_running_totals(p_customer_id integer)
RETURNS TABLE (order_id integer, total numeric, running numeric)
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r record;
v_running numeric := 0;
BEGIN
FOR r IN
SELECT o.id, o.total
FROM orders o
WHERE o.customer_id = p_customer_id
ORDER BY o.id
LOOP
v_running := v_running + r.total;
order_id := r.id;
total := r.total;
running := v_running;
RETURN NEXT;
END LOOP;
END;
$$;
SELECT * FROM order_running_totals(42);The query uses o.id and o.total with an alias. Without the alias, total could mean either the table column or the output variable, and PL/pgSQL would raise an ambiguity error.
Looping over a dynamic query
When the query text is built at run time, use FOR r IN EXECUTE query_text USING ... LOOP. The rules from the dynamic SQL chapter apply: quote identifiers with format('%I', ...) and pass values with USING.
CREATE FUNCTION list_ids(p_table text, p_min integer)
RETURNS SETOF integer
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_id integer;
BEGIN
FOR v_id IN EXECUTE format('SELECT id FROM %I WHERE id > $1 ORDER BY id', p_table)
USING p_min
LOOP
RETURN NEXT v_id;
END LOOP;
END;
$$;Explicit cursors
A cursor is a handle on a running query. The FOR loop already uses one for you. You declare a cursor yourself when you need finer control: reading a few rows at a time, moving backwards, stopping and resuming, or handing the result to the caller.
A cursor goes through four steps: declare, open, fetch, and close.
A bound cursor has its query fixed in the DECLARE section and can take parameters.
CREATE FUNCTION print_big_orders(p_min numeric)
RETURNS integer
LANGUAGE plpgsql
AS $$
DECLARE
cur CURSOR (min_total numeric) FOR
SELECT id, total FROM orders WHERE total > min_total ORDER BY id;
r record;
v_n integer := 0;
BEGIN
OPEN cur(p_min);
LOOP
FETCH cur INTO r;
EXIT WHEN NOT FOUND;
RAISE NOTICE 'order % total %', r.id, r.total;
v_n := v_n + 1;
END LOOP;
CLOSE cur;
RETURN v_n;
END;
$$;FETCH ... INTO sets FOUND to false when no row is left, which is why the loop exits on NOT FOUND. If you do not need manual fetching, FOR r IN cur(p_min) LOOP ... END LOOP opens, fetches, and closes a bound cursor for you.
Other cursor commands
| Command | Effect |
|---|---|
| `OPEN cur FOR query` | Opens an unbound cursor variable with a query |
| `FETCH cur INTO r` | Reads the next row into `r` |
| `FETCH PRIOR`, `FIRST`, `LAST`, `ABSOLUTE n` | Reads other positions, only on a `SCROLL` cursor |
| `MOVE cur` | Moves the position without returning a row |
| `CLOSE cur` | Releases the cursor |
Cursors are closed automatically at the end of the transaction, but closing them yourself keeps long functions tidy.
Returning a cursor to the caller
A variable of type refcursor holds a cursor name. A function can open a cursor and return that name. The caller then fetches rows in whatever batch size it likes, as long as it stays in the same transaction.
CREATE FUNCTION open_orders_cursor(p_min numeric, p_name refcursor DEFAULT 'orders_cur')
RETURNS refcursor
LANGUAGE plpgsql
AS $$
BEGIN
OPEN p_name FOR
SELECT id, total FROM orders WHERE total > p_min ORDER BY id;
RETURN p_name;
END;
$$;
BEGIN;
SELECT open_orders_cursor(500);
FETCH 10 FROM orders_cur;
FETCH 10 FROM orders_cur;
CLOSE orders_cur;
COMMIT;Choosing between the options
| Approach | Use it when | Watch out for |
|---|---|---|
| Single SQL statement | The work can be written as a set operation | Nothing, this is the default choice |
| `FOR r IN query` | Each row needs procedural logic | Row-by-row work is slower than a set operation |
| Explicit cursor | You need to fetch in chunks, move around, or return the cursor | More code, and you must manage open and close |
Common errors
- Updating one row per iteration. A loop that runs an
UPDATEfor every row does one statement execution per row. TryUPDATE ... FROMfirst. - Expecting to see your own changes. The loop reads a snapshot from when it started, so rows you insert inside the loop are not visited.
- Unqualified column names. In
RETURNS TABLEfunctions, a column calledtotalcollides with the output variabletotal. Qualify with a table alias. - Using the loop variable afterwards. An automatically declared loop variable does not exist after
END LOOP. - Fetching from a closed or unopened cursor. This raises an "invalid cursor" style error. Check the order of
OPEN,FETCH, andCLOSE.
Cursors and COMMIT in procedures
Inside a procedure you can call COMMIT in the middle of a loop over a query. Normally a commit closes cursors. A cursor created by a FOR loop is the exception: the first COMMIT or ROLLBACK converts it to a holdable cursor. That means the whole query result is computed at that moment instead of row by row. For a very large result, this can use a lot of memory or temporary space. Batching with LIMIT, as in the archive procedure from the earlier chapter, avoids the problem.
Exercise
A function loops over SELECT id FROM orders and, inside the loop, inserts a new row into orders for each id it reads. Does the loop visit the newly inserted rows? Why or why not?
Show answer
No. The loop reads from a snapshot of the query taken when it starts, so rows inserted inside the loop are not returned. The function ends after visiting only the rows that existed at the start.
Exercise
Write a loop-free statement that gives the same result as total_for_customer, and name one situation where an explicit cursor is a better choice than a FOR loop.
Show answer
SELECT coalesce(sum(total), 0) FROM orders WHERE customer_id = 42; An explicit cursor is better when the function should return a refcursor so the caller can fetch rows in batches. It is also better when you need to move backwards with a SCROLL cursor.