Sub topic 1
What PL/pgSQL Is and When to Use It
PL/pgSQL is PostgreSQL’s procedural language. It adds variables, conditions, loops, and error handling to SQL. You can use it to store application logic inside the database.
This chapter assumes you know basic SELECT, INSERT, UPDATE, DELETE, and JOIN statements. You should also know common PostgreSQL data types and be able to run SQL in psql or another client. Basic programming concepts such as variables and loops are useful.
Prerequisites
You should be comfortable with:
- Writing SQL queries against tables.
- Choosing suitable PostgreSQL data types.
- Calling commands from a SQL client.
- Reading simple conditional and loop logic.
- Understanding that a database transaction groups related changes into one unit.
The role of PL/pgSQL
A normal SQL statement describes a data operation. For example, a query can calculate a total or update matching rows. PL/pgSQL lets you combine several SQL statements with decisions and intermediate values.
A PL/pgSQL routine runs on the PostgreSQL server. The client sends one function call or procedure call instead of sending every individual step. This can reduce network traffic and keep rules close to the data they protect.
A routine is a good fit when it:
- Applies a rule that many applications must share.
- Performs several related database operations.
- Needs conditional logic based on query results.
- Must validate data near the tables it changes.
- Is useful from SQL, scheduled jobs, reports, or multiple services.
Plain SQL is usually better when one query can express the operation clearly. Set-based SQL often performs better than a procedural loop because PostgreSQL can optimize the operation as a whole.
| Use case | Usually prefer |
|---|---|
| Filter, join, or aggregate rows | Plain SQL |
| Reuse a calculation in many queries | SQL or PL/pgSQL function |
| Coordinate several database steps | PL/pgSQL |
| Commit batches independently | Procedure |
| React automatically to row changes | Trigger function |
Functions and procedures
A function returns a value, a row, or a set of rows. You can call it inside SQL expressions or with SELECT.
A procedure is called with CALL. It is intended for an operation rather than a value-producing expression. A procedure can use transaction control such as COMMIT in situations where a function cannot.
The distinction matters when designing an interface:
- Use a function when callers need a result.
- Use a procedure when callers ask the database to perform an operation.
- Use neither when a single clear SQL statement is sufficient.
A small PL/pgSQL function
The following function calculates a price after tax. DECLARE holds local variables, although this example does not need one. BEGIN and END contain the executable statements. The dollar-quoted body keeps the function definition readable.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
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 DEFAULT value lets callers omit rate. The IMMUTABLE attribute tells PostgreSQL that the result depends only on the input arguments. That declaration is appropriate here because the function does not read tables, inspect the current time, or use random values.
A useful mental model
A PL/pgSQL function has an input boundary, a procedural body, and an output boundary.
The function body can read or change database data, depending on its purpose and permissions. Keep the body focused. A routine that mixes validation, reporting, unrelated updates, and external application policy becomes difficult to test and maintain.
> callout note > Start with plain SQL. Add PL/pgSQL when you need procedural control, reusable database-side rules, or a transaction-oriented operation that SQL alone cannot express clearly.
First design questions
Before writing a routine, ask:
- Can one SQL statement solve the problem?
- Should the caller receive a scalar, a row, or a result set?
- Does the routine read data, modify data, or both?
- Must several changes succeed or fail together?
- Will the logic be shared by more than one client?
- Are the declared function attributes accurate?
These questions help you choose the right routine type before its syntax becomes the focus.
Exercise
Should you write a PL/pgSQL function for a query that only filters rows by a supplied status?
Show answer
Usually no. Use a plain parameterized SQL query unless the operation needs additional procedural logic or a reusable database interface.