Sub topic 8
Looping Over Query Results and Using Cursors
This chapter assumes that you know basic SQL and PL/pgSQL blocks, variables, and conditional statements. A query loop lets a function process each row returned by a query. A cursor gives you more explicit control over reading rows, which is useful when a result is large or must be consumed in stages.
Query loops: the usual choice
A FOR loop over a query runs the query and assigns each result row to a record variable. The loop ends automatically when there are no more rows.
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 AS o
WHERE o.customer_id = p_customer_id
LOOP
v_sum := v_sum + r.total;
END LOOP;
RETURN v_sum;
END;
$$;The variable r has the columns returned by the query. You access a column with dot notation, such as r.total.
A query loop is clear when each row needs procedural work:
FOR r IN
SELECT id, total
FROM orders
WHERE customer_id = p_customer_id
LOOP
RAISE NOTICE 'Order % has total %', r.id, r.total;
END LOOP;However, do not use a loop when SQL can perform the whole operation more directly. For example, this is usually faster and simpler than adding totals one row at a time:
SELECT COALESCE(sum(total), 0)
FROM orders
WHERE customer_id = 42;The database can optimize a set-based query. A procedural loop may require more interpreter work and more code.
Explicit cursors
A cursor is a named mechanism for reading a query result incrementally. Declare a cursor, open it, fetch rows, and close it.
CREATE FUNCTION count_large_orders(p_min numeric)
RETURNS integer
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
c_orders CURSOR FOR
SELECT id, total
FROM orders
WHERE total > p_min
ORDER BY id;
r record;
v_count integer := 0;
BEGIN
OPEN c_orders;
LOOP
FETCH c_orders INTO r;
EXIT WHEN NOT FOUND;
v_count := v_count + 1;
RAISE NOTICE 'Large order: %', r.id;
END LOOP;
CLOSE c_orders;
RETURN v_count;
END;
$$;After FETCH, FOUND is true when a row was fetched and false when the cursor has no more rows. EXIT WHEN NOT FOUND must come immediately after the fetch if later statements could change FOUND.
You can also loop through a cursor automatically:
FOR r IN c_orders
LOOP
RAISE NOTICE 'Order %', r.id;
END LOOP;This form handles opening, fetching, and closing for the loop. Use an explicit cursor when you need to fetch a specific number of rows, pause between fetches, or manage cursor state yourself.
Common errors
- Forgetting
CLOSEafter manually opening a cursor can leave resources open until the surrounding transaction ends. - Fetching into variables with incompatible types can cause conversion errors. A
recordvariable adapts to the query shape. - Using an unqualified column such as
totalcan create ambiguity with a parameter or output variable. Qualify it aso.total. - Assuming a cursor survives a commit. A normal cursor is transaction-scoped unless declared with special hold behavior.
Exercise
When should you choose a query FOR loop instead of an explicit cursor?
Show answer
Use a query FOR loop when you need to process every row and do not need manual control over fetching. Use an explicit cursor when you need incremental fetches or cursor state.