DO runs an inline code block written in any trusted procedural language installed in the PostgreSQL instance (PL/pgSQL by default). Because the block is anonymous, PostgreSQL compiles and discards it after execution, making DO ideal for one-off tasks that do not justify a permanent function. The block executes in the current transaction; if the surrounding transaction is rolled back, changes made inside the DO block are also rolled back. A DO block can contain complex control-of-flow, variable declarations, cursors, and exception handling, but it cannot return a result set or be used in a SELECT statement. Optional SECURITY DEFINER allows the block to run with the privileges of its creator; SECURITY INVOKER (default) uses the caller’s rights. You may specify a different language such as plpythonu or plv8 if the language is trusted or the superuser flag allows it. The code must be delimited by a pair of dollar-quoting tags, commonly $$, and terminated with a semicolon after the closing delimiter. Large blocks should be indented for readability. Because the block is parsed each time it runs, heavy repetition inside application code is discouraged in favor of permanent functions.
LANGUAGE lang_name
(text) - Procedural language used to execute the block; default is plpgsql.SECURITY DEFINER | INVOKER
(keyword) - Defines whether the block runs with the privileges of its creator (DEFINER) or caller (INVOKER); default is INVOKER.CREATE FUNCTION, CALL, BEGIN END, RAISE, PL/pgSQL, TRANSACTION
PostgreSQL 9.0
PostgreSQL allows any installed procedural language marked as trusted, such as plpgsql, plpython3u, plperl, or plv8. Superuser rights are required for untrusted languages.
No. It executes within the caller's current transaction. You may wrap the DO block in BEGIN/COMMIT to control commit behavior.
Use CREATE FUNCTION for logic that will be reused, needs to return values, or must be called from other SQL statements. Choose DO for one-time maintenance or migration tasks.
Yes. With PL/pgSQL, use EXECUTE to run dynamic SQL strings constructed at runtime.