You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
PL/pgSQL (Procedural Language/PostgreSQL) is PostgreSQL's built-in procedural language. It extends plain SQL with variables, control flow, loops, and error handling — letting you write complex logic that runs entirely inside the database server.
SQL is declarative — you say what you want, not how to compute it. That works perfectly for most queries, but falls short when you need:
PL/pgSQL provides all of these.
PL/pgSQL code compiles to an internal representation on first execution and is cached in the session. Subsequent calls reuse the cached plan, making PL/pgSQL functions fast for repeated use.
| Benefit | Detail |
|---|---|
| Reduced round-trips | Multiple SQL statements in a single server call |
| Reusability | Write logic once; call it from queries, triggers, or applications |
| Security | Grant EXECUTE on a function without exposing underlying tables |
| Triggers | PL/pgSQL is the standard language for PostgreSQL trigger functions |
DO statement-- Plain SQL: two separate statements, no guarantee they're atomic
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- PL/pgSQL: both updates inside a function, with error handling
CREATE OR REPLACE FUNCTION transfer(from_id INT, to_id INT, amount NUMERIC)
RETURNS VOID LANGUAGE plpgsql AS $$
BEGIN
UPDATE accounts SET balance = balance - amount WHERE id = from_id;
UPDATE accounts SET balance = balance + amount WHERE id = to_id;
EXCEPTION
WHEN OTHERS THEN
RAISE EXCEPTION 'Transfer failed: %', SQLERRM;
END;
$$;
PL/pgSQL function bodies are written as string literals. PostgreSQL uses dollar quoting ($$...$$) instead of single quotes to avoid escaping issues:
CREATE OR REPLACE FUNCTION hello() RETURNS TEXT LANGUAGE plpgsql AS $$
BEGIN
RETURN 'Hello, PL/pgSQL!';
END;
$$;
You can also use named tags like $body$...$body$ for clarity or nesting.
PostgreSQL supports additional languages via extensions:
| Language | Extension |
|---|---|
| Python | PL/Python |
| Perl | PL/Perl |
| JavaScript | PL/V8 |
| R | PL/R |
PL/pgSQL is the default and most widely used.