postgresql_16:6.6.6.6 Looping through Query Results
PostgreSQL 16 > Server Programming > PL/pgSQL — SQL Procedural Language > Control Structures > Looping through Query Results
Using a different type of FOR loop, you can iterate through the results of a query and manipulate that data accordingly. The syntax is: <<*label*>> FOR *target* IN *query* LOOP *statements* END LOOP *label* ; The *target* is a record variable, row variable, or comma-separated list of scalar variables. The *target* is successively assigned each row resulting from the *query* and the loop body is executed for each row. Here is an example: CREATE FUNCTION refresh_mviews() RETURNS integer AS $$ DECLARE mviews RECORD; BEGIN RAISE NOTICE 'Refreshing all materialized views...'; FOR mviews IN SELECT n.nspname AS mv_schema, c.relname AS mv_name, pg_catalog.pg_get_userbyid(c.relowner) AS owner FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) WHERE c.relkind = 'm' ORDER BY 1 LOOP -- Now "mviews" has one record with information about the materialized view RAISE NOTICE 'Refreshing materialized view %.% (owner: %)...', quote_ident(mviews.mv_schema), quote_ident(mviews.mv_name), quote_ident(mviews.owner); EXECUTE format('REFRESH MATERIALIZED VIEW %I.%I', mviews.mv_schema, mviews.mv_name); END LOOP; RAISE NOTICE 'Done refreshing materialized views.'; RETURN 1; END; $$ LANGUAGE plpgsql; If the loop is terminated by an EXIT statement, the last assigned row value is still accessible after the loop.
The *query* used in this type of FOR statement can be any SQL command that returns rows to the caller: SELECT is the most common case, but you can also use INSERT, UPDATE, or DELETE with a RETURNING clause. Some utility commands such as EXPLAIN will work too.
PL/pgSQL variables are replaced by query parameters, and the query plan is cached for possible re-use, as discussed in detail in (see postgresql_16:6.6.11.1) and (see postgresql_16:6.6.11.2).
The FOR-IN-EXECUTE statement is another way to iterate over rows: <<*label*>> FOR *target* IN EXECUTE *text_expression* USING *expression* , ... LOOP *statements* END LOOP *label* ; This is like the previous form, except that the source query is specified as a string expression, which is evaluated and replanned on each entry to the FOR loop. This allows the programmer to choose the speed of a preplanned query or the flexibility of a dynamic query, just as with a plain EXECUTE statement. As with EXECUTE, parameter values can be inserted into the dynamic command via USING.
Another way to specify the query whose results should be iterated through is to declare it as a cursor. This is described in (see postgresql_16:6.6.7.4).