DO(7)

✨ DO(7) ✨

okay bestie, this is the DO page from the PostgreSQL 18.6 Documentation, and it's literally the "just run this code real quick" icon we deserve πŸ’…


🌸 NAME 🌸

DO β€” execute an anonymous code block

no cap, that's the whole vibe: anonymous code, zero name, all vibes πŸ¦‹


πŸŽ€ SYNOPSIS πŸŽ€

DO [ LANGUAGE lang_name ] code

look at her. so simple. so powerful. she ate πŸ’–


✨ DESCRIPTION ✨

So DO runs an anonymous code block β€” which is basically a transient anonymous function written in some procedural language. No name, no commitment, just vibes and execution. 🌈

The code block gets treated like it's the body of a function that takes no parameters and returns void. It's parsed and executed a single time. One and done, periodt.

The optional LANGUAGE clause is flexible like that β€” you can write it either before or after the code block. She's not picky, she's iconic πŸ‘‘


πŸ’– PARAMETERS πŸ’–

  • code β€” the procedural language code that's actually getting executed. It must be specified as a string literal, exactly like in CREATE FUNCTION. Using a dollar-quoted literal is the recommended move, fr fr 🫢
  • lang_name β€” the name of the procedural language your code is written in. If you leave it out, the default is plpgsql. (yes queen, lowercase, exactly like that) πŸ’œ

πŸ”₯ NOTES πŸ”₯

  • The procedural language you wanna use has to already be installed in the current database via CREATE EXTENSION. plpgsql comes installed by default, but the other languages? Not so much bestie 😭
  • You need USAGE privilege on the procedural language β€” or you gotta be a superuser if the language is untrusted. Same privilege requirement as creating a function in that language, iykyk.
  • > ⚠️ okay important one: if DO is executed inside a transaction block, then the procedure code cannot execute transaction control statements. Transaction control statements are only allowed if DO is executed in its own transaction. So like... don't do that. 🫣

🌈 EXAMPLES 🌈

Grant all privileges on all views in schema public to role webuser β€” watch her work πŸ’…:

DO $$DECLARE r record;
BEGIN
    FOR r IN SELECT table_schema, table_name FROM information_schema.tables
             WHERE table_type = 'VIEW' AND table_schema = 'public'
    LOOP
        EXECUTE 'GRANT ALL ON ' || quote_ident(r.table_schema) || '.' || quote_ident(r.table_name) || ' TO webuser';
    END LOOP;
END$$;

literally a whole for-loop inside a DO block. she's serving ✨


πŸ’€ COMPATIBILITY πŸ’€

There is no DO statement in the SQL standard. Not a thing. Never was. PostgreSQL just said "we're doing our own thing" and honestly? respect πŸ™ˆ


πŸ¦‹ SEE ALSO πŸ¦‹


and that's the whole page, bestie!! 🌸 This was PostgreSQL 18.6, documented in 2026 β€” so go write your anonymous code blocks and slay responsibly πŸŽ€πŸ’–πŸ«Ά