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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- What objects does the SQL involve?
- The references are `pg_stat_user_tables`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.