Sub topic 15
When to Use SQL and When to Use PL/pgSQL
Assume you know basic SQL statements, PostgreSQL data types, schemas, and roles. This chapter focuses on choosing the implementation language for a PostgreSQL function.
PostgreSQL supports several function languages. The two common choices are:
LANGUAGE sql, which describes one or more SQL statements.LANGUAGE plpgsql, which adds procedural features such as variables, conditions, loops, and exception handling.
Start with SQL when the logic is a query
Use a SQL function when the function can be expressed as a direct SQL statement or a short sequence of statements. SQL functions work well for:
- Calculating a value from input arguments.
- Selecting rows from one or more tables.
- Inserting, updating, or deleting rows and returning a result.
- Composing reusable query logic.
CREATE FUNCTION order_total(p_customer_id integer)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT COALESCE(sum(total), 0)
FROM orders
WHERE customer_id = p_customer_id;
$$;
SELECT order_total(42);This function has no local variables or branching. Its behavior is visible in the SQL statement, so LANGUAGE sql is the simpler choice.
A SQL function can contain multiple statements, but the statements run in order and the final statement supplies the function's result. If you need procedural decisions between statements, SQL usually becomes awkward.
Use PL/pgSQL for procedural logic
PL/pgSQL is PostgreSQL's procedural language. Choose it when the function must make decisions, repeat work, store intermediate values, or handle errors.
CREATE FUNCTION shipping_fee(p_total numeric)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
fee numeric;
BEGIN
IF p_total >= 100 THEN
fee := 0;
ELSE
fee := 9.99;
END IF;
RETURN fee;
END;
$$;
SELECT shipping_fee(125);The DECLARE section defines a local variable. The IF statement chooses a path, and RETURN supplies the result. The BEGIN and END here are PL/pgSQL block markers, not a SQL function's BEGIN ATOMIC body.
PL/pgSQL is also useful for loops, row-by-row processing, dynamic SQL, and controlled exception handling. However, row-by-row code can be slower than one set-based SQL statement. Before writing a loop, check whether a single SELECT, INSERT, UPDATE, or DELETE can perform the operation.
Compare the trade-offs
| Need | SQL function | PL/pgSQL function |
|---|---|---|
| Direct query or calculation | Usually the best fit | Works, but adds ceremony |
| Variables and branching | Limited | Built in |
| Loops and exception blocks | Not convenient | Built in |
| Planner optimization | Often easier to inline | Usually treated as a function call |
| Dynamic SQL | Not flexible | Use `EXECUTE` with careful quoting |
The PostgreSQL planner can inline some simple SQL functions into the surrounding query. This can expose the function's expressions and filters to query planning. PL/pgSQL normally keeps its internal statements behind a function-call boundary. This difference can affect performance, especially inside queries that process many rows.
Do not choose SQL only for possible inlining. Correctness and maintainability come first. Measure important queries with EXPLAIN (ANALYZE, BUFFERS).
A practical decision
Use LANGUAGE sql when the function is a named query, calculation, or data-modifying statement. Use LANGUAGE plpgsql when the function is a small program with control flow. If a PL/pgSQL function only contains one SQL statement and a return value, simplify it to SQL.
Exercise
Which language is the better default for a function that selects a customer's five most recent orders and returns them as a table?
Show answer
Use LANGUAGE sql. The function is a query with no variables, branching, loops, or exception handling.