FOR Record Loop Iterates Query Rows

A PL/pgSQL FOR loop can walk a SELECT result row by row: the loop target is assigned each row, and EXIT stops early while keeping the last row readable.

SqlData Integrity

Code

snippet
CREATE OR REPLACE FUNCTION summarize_partitions() RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
    part RECORD;        -- 循环目标:每轮被赋值为一行
    biggest text := '';
BEGIN
    FOR part IN
        SELECT relname, n_live_tup
        FROM pg_stat_user_tables
        WHERE schemaname = 'public'
        ORDER BY n_live_tup DESC
    LOOP
        RAISE NOTICE '%: % rows', part.relname, part.n_live_tup;
        IF biggest = '' THEN
            biggest := part.relname;   -- 首轮记录最大表
        END IF;
    END LOOP;

    RAISE NOTICE 'biggest: %', biggest;

    -- EXIT 提前跳出:最后一次赋值的行在循环外仍可读
    FOR part IN SELECT relname FROM pg_stat_user_tables LIMIT 5 LOOP
        EXIT WHEN part.relname LIKE 'tmp%';
        RAISE NOTICE 'kept: %', part.relname;
    END LOOP;
END $$;

SELECT summarize_partitions();

How the snippet works

SELECT / CREATE statements share the script, touching pg_stat_user_tables.

In terms of clauses, the statements use: a WHERE clause limiting a statement to the rows that qualify; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Applying it

Run the statement against the pg_stat_user_tables table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

SELECT summarize_partitions();

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `pg_stat_user_tables`.