Do Block Loops With Notice
Run anonymous procedural code inline with a DO block, using an integer FOR loop and RAISE NOTICE to emit progress lines from a psql session.
Code
-- DO 块执行一次性匿名过程:不需要先 CREATE FUNCTION
DO $$
DECLARE
total integer := 0;
moved integer;
BEGIN
-- 整数 FOR 循环:边界含两端
FOR i IN 1..3 LOOP
total := total + i;
-- RAISE NOTICE 是过程块的进度输出,不中断执行
RAISE NOTICE 'step %, running total %', i, total;
END LOOP;
-- 倒序 FOR IN REVERSE:同一循环结构换个方向跑
FOR i IN REVERSE 3..1 LOOP
RAISE NOTICE 'countdown %', i;
END LOOP;
-- 过程块里也能碰表:建临时表、插入、聚合回读
CREATE TEMP TABLE demo_totals (step integer, value integer);
INSERT INTO demo_totals VALUES (1, total), (2, total * 2);
SELECT count(*) INTO moved FROM demo_totals;
RAISE NOTICE 'rows staged: %, final total: %', moved, total;
END $$;
-- NOTICE: step 1, running total 1
-- NOTICE: step 2, running total 3
-- NOTICE: step 3, running total 6
-- NOTICE: countdown 3
-- NOTICE: countdown 2
-- NOTICE: countdown 1
-- NOTICE: rows staged: 2, final total: 6
-- $$ 美元引用免转义:块内单引号无需翻倍
DO $$
BEGIN
RAISE NOTICE 'it''s fine to quote inside dollar quoting';
END $$;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with demo_totals and moved among the objects involved.
demo_totals is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Mechanically, the statements are built from: COUNT aggregation.
Using it
The file is self-contained: it creates the session-local tables it uses (demo_totals), so run it as a whole against a scratch database.
Key statements
CREATE TEMP TABLE demo_totals (step integer, value integer);
INSERT INTO demo_totals VALUES (1, total), (2, total * 2);
SELECT count(*) INTO moved FROM demo_totals;
Interactive Tools for This Topic
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.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.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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- What are the relations in play here?
- The references are `demo_totals`, `moved`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.