Discover how to run quick database fixes without the hassle of permanent functions!
Why DO blocks for anonymous code in PostgreSQL? - Purpose & Use Cases
Imagine you want to run a quick set of commands in your database to fix some data or test a small logic piece without creating a full stored procedure.
You try to write and save a function every time, but it feels like too much work for a simple task.
Writing full functions for small tasks is slow and clutters your database with many one-time-use functions.
It's easy to make mistakes copying and pasting code, and cleaning up afterward is a hassle.
DO blocks let you write and run anonymous code directly in the database without saving it permanently.
This means you can quickly test or fix things with simple, reusable blocks that disappear after running.
CREATE FUNCTION temp_fix() RETURNS void AS $$ BEGIN UPDATE table SET col = val; END; $$ LANGUAGE plpgsql; SELECT temp_fix(); DROP FUNCTION temp_fix();
DO $$ BEGIN UPDATE table SET col = val; END; $$ LANGUAGE plpgsql;
You can run quick, temporary code snippets safely and efficiently without cluttering your database.
A developer needs to fix a few rows in a table immediately during debugging without creating permanent functions.
DO blocks run anonymous code without saving it.
They speed up quick fixes and tests.
They keep your database clean from temporary functions.