0
0
PostgreSQLquery~5 mins

DO blocks for anonymous code in PostgreSQL

Choose your learning style9 modes available
Introduction
DO blocks let you run small pieces of code inside the database without creating a permanent function.
You want to test a quick piece of code without saving it.
You need to perform a one-time task like updating data or logging.
You want to run procedural logic directly in the database.
You want to execute code that does not return data but performs actions.
You want to automate small maintenance tasks inside the database.
Syntax
PostgreSQL
DO $$
BEGIN
  -- your code here
END;
$$ LANGUAGE plpgsql;
The code inside DO runs immediately and is anonymous (no name).
Use LANGUAGE plpgsql to write procedural code in PostgreSQL.
Examples
This prints a simple message to the console.
PostgreSQL
DO $$
BEGIN
  RAISE NOTICE 'Hello, world!';
END;
$$ LANGUAGE plpgsql;
This increases salary by 10% for all employees in Sales.
PostgreSQL
DO $$
BEGIN
  UPDATE employees SET salary = salary * 1.1 WHERE department = 'Sales';
END;
$$ LANGUAGE plpgsql;
This counts employees and prints the total.
PostgreSQL
DO $$
DECLARE
  count_employees INTEGER;
BEGIN
  SELECT COUNT(*) INTO count_employees FROM employees;
  RAISE NOTICE 'Total employees: %', count_employees;
END;
$$ LANGUAGE plpgsql;
Sample Program
This block prints messages before and after a 1-second pause.
PostgreSQL
DO $$
BEGIN
  RAISE NOTICE 'Starting anonymous block';
  PERFORM pg_sleep(1); -- wait for 1 second
  RAISE NOTICE 'Finished anonymous block';
END;
$$ LANGUAGE plpgsql;
OutputSuccess
Important Notes
DO blocks do not return query results; they are for running code only.
Use RAISE NOTICE to print messages for debugging or information.
You can declare variables inside DO blocks using DECLARE.
Summary
DO blocks run anonymous procedural code immediately in PostgreSQL.
They are useful for quick tasks without creating permanent functions.
Use LANGUAGE plpgsql and write code inside BEGIN...END.