Sub topic 15
When to use SQL and when to use PL/pgSQL
This chapter assumes you can already write a SQL function with CREATE FUNCTION. It also assumes you know the volatility categories and STRICT, and have read the earlier chapter on planner inlining. It helps you choose between LANGUAGE sql and LANGUAGE plpgsql for a given task.
What each language gives you
A SQL function is a list of SQL statements. PostgreSQL runs them in order and returns the result of the last one. The language has no variables, no IF, no loops, and no way to catch an error.
PL/pgSQL is a procedural language that wraps SQL. It adds:
- Local variables declared in a
DECLAREblock. - Control flow with
IF,CASE,LOOP,WHILEandFOR. - Error handling with
RAISEandEXCEPTIONblocks. - Dynamic SQL with
EXECUTE. - Status checks such as
FOUNDandGET DIAGNOSTICS. COMMITandROLLBACKinside procedures.
These are the only reasons to leave SQL. The two languages differ in what they can express, and they also differ in how the planner treats them.
| Concern | `LANGUAGE sql` | `LANGUAGE plpgsql` |
|---|---|---|
| Branching and loops | Not available. Use `CASE` inside a query. | `IF`, `CASE`, `LOOP`, `FOR` |
| Intermediate variables | Not available. Use a CTE or subquery. | `DECLARE` and `:=` |
| Error handling | None. The error propagates. | `EXCEPTION WHEN ... THEN` |
| Dynamic SQL | Not available | `EXECUTE format(...)` |
| Planner inlining | Possible for simple bodies | Never inlined |
| Body checked at creation | Yes, with `BEGIN ATOMIC` bodies or `check_function_bodies` on | Syntax only. Embedded SQL is checked at first run. |
| Transaction control in procedures | Not covered here | `COMMIT` and `ROLLBACK` |
Default to SQL for query-shaped work
If the function is one query, or a short sequence of statements with no decisions, write it in SQL. The function stays short and it can be inlined. Inlining is the main performance difference between the two languages.
CREATE FUNCTION is_adult_sql(age int)
RETURNS boolean
LANGUAGE sql
IMMUTABLE
AS $$
SELECT age >= 18;
$$;
CREATE FUNCTION is_adult_plpgsql(age int)
RETURNS boolean
LANGUAGE plpgsql
IMMUTABLE
AS $$
BEGIN
RETURN age >= 18;
END;
$$;Both functions return the same answers. Compare how the planner treats them:
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM generate_series(1, 100) AS g(age)
WHERE is_adult_sql(g.age);
EXPLAIN (VERBOSE, COSTS OFF)
SELECT * FROM generate_series(1, 100) AS g(age)
WHERE is_adult_plpgsql(g.age);In the first plan the filter is the expanded expression g.age >= 18. The planner has replaced the function call with its body, so it can use statistics and indexes on age. In the second plan the filter is still the call is_adult_plpgsql(g.age). The planner treats the call as a black box, assumes a default selectivity, and cannot use an index on the expression inside.
On a large table this difference decides whether a query is fast or slow. It also affects table-returning functions, because a simple SQL function in FROM can be merged into the outer query.
Switch to PL/pgSQL when you need procedure logic
Choose PL/pgSQL when the work depends on intermediate results. This function validates input, updates a row, and reports failure with clear messages:
-- Assumes a table orders(id int primary key, total numeric)
CREATE FUNCTION apply_discount(p_order_id int, p_pct numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $$
DECLARE
v_total numeric;
BEGIN
IF p_pct < 0 OR p_pct > 50 THEN
RAISE EXCEPTION 'discount % is out of range', p_pct
USING ERRCODE = '22023';
END IF;
UPDATE orders
SET total = total * (1 - p_pct / 100)
WHERE id = p_order_id
RETURNING total INTO v_total;
IF NOT FOUND THEN
RAISE EXCEPTION 'order % not found', p_order_id;
END IF;
RETURN v_total;
END;
$$;A SQL function can run the UPDATE ... RETURNING. It cannot reject a bad percentage, and it cannot turn "no row updated" into an error. It would return NULL and the caller would have to guess why.
Dynamic SQL is the other common reason. SQL functions cannot build a statement from a table name at run time. PL/pgSQL can, with format() to quote the identifier safely:
CREATE FUNCTION count_rows(p_table regclass)
RETURNS bigint
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
n bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %s', p_table) INTO n;
RETURN n;
END;
$$;
SELECT count_rows('orders');Taking the argument as regclass means PostgreSQL checks that the table exists. Printing it with %s produces a correctly quoted, schema-qualified name. For a plain text identifier, use %I instead.
A decision path
Rewrite logic as a query first
Many functions that look like they need PL/pgSQL do not. Before you reach for it, check whether SQL can express the logic:
- A conditional value becomes
CASE WHEN ... THEN ... END. - A temporary variable becomes a CTE or a subquery.
- A loop that builds a result becomes a set-based
SELECTwithgenerate_series, a join, or an aggregate. - A default for missing data becomes
COALESCE.
This SQL function replaces a loop-and-IF approach:
CREATE FUNCTION shipping_cost(weight_kg numeric, express boolean)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT CASE
WHEN weight_kg <= 1 THEN 5
WHEN weight_kg <= 10 THEN 5 + (weight_kg - 1) * 1.5
ELSE 20
END * CASE WHEN express THEN 2 ELSE 1 END;
$$;Row-by-row loops in PL/pgSQL are usually slower than one set-based statement. A FOR ... LOOP that runs one UPDATE per row pays a statement execution for every iteration. A single UPDATE ... FROM pays it once.
Common problems
Late errors in PL/pgSQL
PL/pgSQL checks syntax when you create the function. It checks the embedded SQL, such as table and column names, only when that statement first runs. A typo in a rarely used branch can survive for months. SQL functions fail at creation time, which is better. Test every branch of a PL/pgSQL function, and consider the plpgsql_check extension for static analysis.
Variables that shadow columns
In PL/pgSQL, a variable named total and a column named total are ambiguous. By default PostgreSQL raises an error. Prefix parameters and variables (p_, v_), as the examples in this chapter do, or qualify columns with a table alias. SQL functions have a milder form of this problem. A parameter name that matches a column loses to the column.
Exception blocks are not free
A BEGIN ... EXCEPTION WHEN ... END block starts a subtransaction. That costs time, and in a loop it can use subtransaction slots. Use it where you need to recover from an error, not as defensive padding. Often INSERT ... ON CONFLICT DO NOTHING removes the need to catch a unique violation.
Plan caching
PL/pgSQL caches plans for its embedded statements after a few executions in the same session. Usually that helps. A generic cached plan can be poor for queries whose best plan depends on parameter values. If you see this, test with plan_cache_mode before rewriting the function.
Mixing the two
The choice is per function, not per application. A common pattern is to keep the queries in small inlinable SQL functions and write PL/pgSQL only for the orchestration around them. This keeps each unit simple, and the planner still sees through the query parts when they are used in other queries.
A rough guide:
- Start with SQL.
- Move to PL/pgSQL when a requirement needs one of its features, and name that feature in a comment.
- Keep the PL/pgSQL body short, and call SQL functions for reusable query logic.
- Check
EXPLAIN VERBOSEon any function used in aWHEREclause or a largeSELECTlist.
Exercise
A function is_valid_email(text) checks $1 ~ '^[^@]+@[^@]+$' and is called in the WHERE clause of queries over a 50-million-row table. A colleague rewrote it in PL/pgSQL "for readability", and the queries slowed down. Explain the likely cause and how you would confirm it.
Show answer
The SQL version can be inlined, so the planner sees the regular-expression expression directly. The PL/pgSQL version is never inlined, so the planner treats each call as an opaque function with default cost and selectivity and cannot optimize the expression. To confirm, run EXPLAIN (VERBOSE) on a query using each version. The SQL version shows the expanded expression in the filter and the PL/pgSQL version shows the function call. The fix is to restore LANGUAGE sql, keeping the IMMUTABLE and STRICT markings.
Exercise
For each requirement, say whether SQL is enough or whether you need PL/pgSQL: (a) return the five latest rows from a table for a given customer; (b) raise a custom error when a stock quantity would go negative; (c) run SELECT count(*) against a table whose name is passed in as an argument.
Show answer
(a) SQL is enough. It is a single query, and LIMIT handles the five rows. (b) PL/pgSQL is needed, because it requires a condition and a custom error with RAISE EXCEPTION. (c) PL/pgSQL is needed, because the table name is only known at run time and requires EXECUTE format(...).