Sub topic 1
What PL/pgSQL is and when to use it
Prerequisites
This chapter assumes you already know the following:
- Basic SQL: SELECT, INSERT, UPDATE, DELETE, and JOIN.
- PostgreSQL data types and how tables are defined.
- How to run statements in
psqlor another SQL client. - Basic programming ideas: variables, conditionals, and loops.
You do not need to have written any server-side code before. This chapter explains what PL/pgSQL is, how it runs, and how to decide whether a piece of logic belongs in the database at all. The syntax comes in the next chapters.
What PL/pgSQL is
PL/pgSQL is a procedural language that PostgreSQL ships with. "Procedural" means you can write step-by-step code with variables, IF statements, loops, and error handling. Plain SQL is declarative: you describe the result you want, and the planner decides how to get it. PL/pgSQL adds the control structures SQL lacks.
The code runs inside the database server. You store it with CREATE FUNCTION or CREATE PROCEDURE, and PostgreSQL keeps it in the system catalog next to your tables. Any client that can connect can then call it by name.
PL/pgSQL is one of several procedural languages for PostgreSQL. It is installed by default in every database, and it is the most common choice for database logic.
| Language | Typical use |
|---|---|
| SQL (`LANGUAGE sql`) | Wrapping one query or a short sequence of statements. No variables or control flow. |
| PL/pgSQL | Multi-step logic, branching, loops, error handling, triggers, procedures with transaction control. |
| PL/Python, PL/Perl, PL/Tcl | Logic that needs a general-purpose language or its libraries. These are extensions and may need a separate install. |
| C | Maximum speed and access to server internals. Requires compiling and trusted deployment. |
A good rule is to start with plain SQL. If that cannot express what you need, move to PL/pgSQL. Reach for another language only when PL/pgSQL cannot do the job.
How it runs
Database code runs in the same process that handles your connection. When you call a function, PostgreSQL does the following:
- It finds the function by name and argument types.
- On the first call in a session, it compiles the function body into an internal form.
- It runs each statement. Embedded SQL statements are handed to the normal planner and executor.
- It returns the result to the caller.
PL/pgSQL does not compile to machine code. It is interpreted. Each expression and each SQL statement inside it is evaluated through the regular SQL machinery. Two consequences follow:
- Embedded SQL statements are as fast as the same SQL run directly, because the same planner handles them.
- Pure computation in PL/pgSQL, such as a tight arithmetic loop, is slower than in a compiled language.
PostgreSQL caches plans for embedded statements within a session. This saves repeated planning work, and it occasionally causes surprises that a later chapter on performance covers.
A first look
The example below is a complete function. Do not worry about every keyword yet. The next chapter covers the structure in detail. It adds sales tax to a price, with a default rate.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN round(price * (1 + rate), 2);
END;
$$;
SELECT add_tax(100);
SELECT add_tax(100, rate => 0.07);The first call returns 120.00, using the default rate of 0.2. The second passes the rate by name and returns 107.00.
Notice three things:
- The body is a string.
$$ ... $$is dollar quoting, which lets you write the body without escaping single quotes inside it. LANGUAGE plpgsqltells PostgreSQL which interpreter to use for that string.- The function is called inside a normal
SELECT, like a built-in function such asround.
This particular function does not need PL/pgSQL. A single LANGUAGE sql function would work and might run faster, since PostgreSQL can inline simple SQL functions into the calling query. It appears here only to show the shape.
Why move logic into the database
Server-side code has real benefits when used for the right jobs.
- Fewer round trips. A client that runs ten dependent queries pays network latency ten times. A function runs all ten inside the server and returns once.
- Data stays close. Work that reads many rows and returns one summary avoids sending those rows over the network.
- One implementation for every client. If a web app, a batch job, and an analyst's script all call the same function, the rule is written once.
- Enforced rules. Triggers run whatever client made the change. A rule such as "stamp
updated_aton every update" cannot be skipped by a client that forgets it. - Controlled access. Functions can run with the privileges of their owner. You can give a role permission to call a function without giving it direct access to the tables behind it.
- Atomic units of work. A function runs inside the caller's transaction, so all its changes commit or roll back together.
Why not to move logic into the database
The same properties have costs. Weigh these before you commit.
- Plain SQL is usually better for set operations. If one
UPDATE ... FROMdoes the job, a loop that updates row by row is slower and longer. The planner can optimize a single statement. It cannot see inside a loop. - The database is hard to scale out. Application servers are easy to add. A primary database server is usually a single machine. Heavy computation inside it competes with queries from every other client.
- Testing and tooling are weaker. Application code has mature debuggers, unit test frameworks, and code review habits. Database code needs deliberate effort to match them.
- Versioning is easy to neglect. Functions live in the database, not in your repository, unless you keep the definitions in migration files. Without that, you cannot tell which version runs in production.
- Logic becomes hidden. A trigger that changes data surprises developers who only read the application code.
- Portability drops. PL/pgSQL is specific to PostgreSQL. Moving to another database means rewriting the code.
- Network calls and slow work do not belong there. A function that holds a transaction open while it waits on something slow keeps locks and connections tied up.
Decision criteria
Use these questions to choose where a piece of logic should live.
| Question | If yes, lean toward |
|---|---|
| Can one SQL statement express it? | Plain SQL, or a `LANGUAGE sql` function if you need reuse. |
| Does it need variables, branching, or loops over intermediate results? | PL/pgSQL. |
| Does it touch many rows and return little data? | A function in the database. |
| Must the rule hold for every client, including ad hoc ones? | A trigger or constraint. Try a constraint first. |
| Does it need to commit part of its work before finishing? | A procedure, covered in a later chapter. |
| Does it call external services, send email, or need rich libraries? | The application, or a job queue outside the database. |
| Does it change often and ship with the app? | The application, unless the data-side benefits outweigh deployment effort. |
Constraints deserve a note. CHECK, UNIQUE, FOREIGN KEY, and NOT NULL express many rules declaratively. They are cheaper to maintain and are understood by the planner and by every developer. Write a trigger only when a constraint cannot express the rule.
Functions, procedures, and triggers
PL/pgSQL code appears in three forms. Later chapters teach each one.
- Functions are created with
CREATE FUNCTION. They are called inside SQL expressions, such as in aSELECTlist or aWHEREclause, and they return a value or a set of rows. They cannot commit or roll back the transaction they run in. - Procedures are created with
CREATE PROCEDURE. They are run withCALL. They do not return a value in the same way, and they can useCOMMITandROLLBACKinside their body. This makes them suitable for long batch jobs. - Trigger functions are functions with the return type
trigger. PostgreSQL runs them automatically before or after anINSERT,UPDATE, orDELETE.
Procedures were added in PostgreSQL 11. Before that, only functions existed, and transaction control inside the database was not possible.
Trying it yourself
Check that the language is available in your database:
SELECT lanname, lanpltrusted
FROM pg_language
WHERE lanname = 'plpgsql';You should get one row, with lanpltrusted set to true. "Trusted" means ordinary users, not only superusers, can create functions in the language, because it cannot access the server's file system.
Next, list the user-defined functions in your database. This query reads the system catalog pg_proc, where function definitions are stored.
SELECT n.nspname AS schema,
p.proname AS name,
pg_get_function_arguments(p.oid) AS arguments,
l.lanname AS language
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
JOIN pg_language l ON l.oid = p.prolang
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY n.nspname, p.proname;After you create add_tax, it should appear in this list. In psql, you can also run \df to list functions and \sf add_tax to print the stored source.
Common mistakes at this stage
- Treating PL/pgSQL like application code. Writing row-by-row loops where a join or aggregate would do is the most frequent problem.
- Putting business rules in triggers first. Triggers hide behavior. Use constraints first, and document each trigger you add.
- Forgetting that the function runs in the caller's transaction. If the caller rolls back, everything the function did rolls back too. This is useful, but you must expect it.
- Not storing definitions in version control. Keep every
CREATE FUNCTIONin a migration or schema file, and useCREATE OR REPLACE FUNCTIONto update it. - Assuming everything needs a function. Many tasks need only a view, a constraint, or a well-written query.
Exercise
A report needs the total of all orders per customer for 2 million rows. A teammate proposes a PL/pgSQL function that loops over every order and adds to a variable for each customer. What would you suggest instead, and why?
Show answer
Use a single set-based query, such as SELECT customerid, sum(total) FROM orders GROUP BY customerid. The planner can optimize one statement with an efficient aggregate. A row-by-row loop adds per-row interpreter overhead and gives the planner nothing to optimize. A function is still useful if the report must be reused by many clients, but its body should wrap the grouped query, not loop.
Exercise
Name two situations from this chapter where a function or trigger in the database is a better fit than application code, and one where it is not.
Show answer
Better fit: a rule that must hold for every client, such as stamping updated_at with a trigger, and logic that reads many rows but returns a small result, which avoids network round trips. Not a good fit: calling an external service such as sending email, because the work is slow, holds the transaction open, and belongs in the application or a job queue.