Quick revision
The short answer
A PL/pgSQL function open_total(p_customer bigint) RETURNS numeric can return coalesce(sum(amount), 0) over the customer's open invoices, marked STABLE because it only reads. A FUNCTION returns a value and is called inside SQL, such as SELECT open_total(42), and it can never COMMIT or ROLLBACK; a PROCEDURE, available since PostgreSQL 11, is invoked with CALL, returns values through OUT parameters, and may commit inside its body when it is not called inside an outer transaction block.
What to remember
In this answer, we wrote open_total as a STABLE PL/pgSQL function that sums open invoices and returns 0 instead of NULL when there are none. We saw that volatility labels tell the planner what it may cache, and that wrong labels silently give wrong results. Functions return values inside SQL and can never commit, while procedures, since PostgreSQL 11, are called with CALL, return OUT parameters and may commit when not inside an outer transaction block. Plain SQL functions can be inlined, which PL/pgSQL functions never are.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A PL/pgSQL function open_total(p_customer bigint) RETURNS numeric can return coalesce(sum(amount), 0) over the customer's open invoices, marked STABLE because it only reads. A FUNCTION returns a value and is called inside SQL, such as SELECT open_total(42), and it can never COMMIT or ROLLBACK; a PROCEDURE, available since PostgreSQL 11, is invoked with CALL, returns values through OUT parameters, and may commit inside its body when it is not called inside an outer transaction block.
Why this question is asked
Database functions come up in Java interviews because many systems keep some logic close to the data, and because the difference between a function and a procedure in PostgreSQL is easy to get wrong: they look almost the same, but they behave differently around transactions. In this answer, we will write the function step by step, call it, look at volatility labels and why a wrong one gives wrong results, compare it with a procedure that commits in batches, and finish with plain SQL functions and SECURITY DEFINER.
1Writing the Function
A function in PostgreSQL has a name, typed parameters, a return type, a language and a body. PL/pgSQL is PostgreSQL's procedural language, which adds variables, IF and loops to SQL. The body is written between dollar quotes, $$ ... $$, so we do not have to escape single quotes inside it.
Notice the coalesce. sum() over zero rows returns NULL, not 0, and callers usually expect a number, so we convert it. The p_ prefix on the parameter is a habit that avoids a name clash: if the parameter were called customer_id, PL/pgSQL could not tell it from the column of the same name and would raise an ambiguity error.
2Volatility Labels: What the Planner May Assume
STABLE is a promise to the planner. PostgreSQL has three volatility labels. IMMUTABLE means the result depends only on the arguments, forever, like lower(text); the planner may compute it once at planning time and indexes may be built on it. STABLE means the result does not change within one statement for the same arguments, though it may read tables; the planner may evaluate it once per statement and use it in index conditions. VOLATILE, the default, means anything can change, so it is called for every row and never optimised away.
Wrong labels give wrong results, not errors. If we marked open_total IMMUTABLE, PostgreSQL could fold SELECT open_total(42) into a constant inside a cached plan, or an index built on it would hold values that never change when invoices do, so queries would return stale totals. The safe rule is to use the most restrictive label that is truly correct: STABLE for functions that read tables, VOLATILE for functions that write or call random() or clock_timestamp().
3Function Versus Procedure
A function returns a value and runs inside the statement that calls it, so it always runs inside that statement's transaction. That is why a function can never COMMIT or ROLLBACK: it would end the transaction of the query that is still using its result. A procedure, added in PostgreSQL 11, is not part of an expression. It is invoked on its own with CALL, returns results through OUT or INOUT parameters (OUT parameters for procedures are supported since PostgreSQL 14), and, when CALL is executed on its own rather than inside an explicit BEGIN block, it may COMMIT and ROLLBACK inside its body. That makes procedures the right tool for batch jobs that must commit as they go.
| FUNCTION | PROCEDURE | |
|---|---|---|
| How it is called | inside SQL: SELECT open_total(42) | on its own: CALL proc(...) |
| Returns | a value, a row or a set | OUT or INOUT parameters |
| COMMIT / ROLLBACK inside | never | yes, if CALL is not in a BEGIN block |
| Usable in WHERE, joins, indexes | yes | no |
| Available since | always | PostgreSQL 11 |
Notice the last call. Inside an explicit transaction block, the procedure cannot commit, because the transaction belongs to the caller. This matters from Java: a JDBC connection with autocommit off, or a Spring @Transactional method, always has a transaction open, so a committing procedure fails the same way.
4Plain SQL Functions Can Be Inlined
For a function whose body is a single query, LANGUAGE sql is often the better choice. The planner can inline a simple SQL function, which means it replaces the call with the function's query and optimises the whole statement together, using indexes and join strategies across the boundary. A PL/pgSQL function is never inlined: the planner sees it as a black box that is called and returns a value, and its internal queries are planned separately.
So we use PL/pgSQL when we need variables, branching, loops or exception handling, and plain SQL when the body is one query. Inlining has conditions, for example the function must not be SECURITY DEFINER and must have a suitable volatility label, so check your version's rules if inlining matters for a hot path.
5Follow-up questions
When would you mark a function SECURITY DEFINER, and what is the risk?
SECURITY DEFINER runs the function with its owner's privileges instead of the caller's, which lets us grant a narrow operation, such as reading one customer's total, to a role that has no access to the invoice table. The risk is privilege escalation: if the function builds dynamic SQL from input, or resolves object names through a search_path the caller controls, the caller can make it run their code with the owner's rights. We always set a fixed search_path on the function (SET search_path = pg_catalog, app), avoid dynamic SQL or quote it with format('%I', ...) and parameters, revoke EXECUTE from PUBLIC and grant it only to the roles that need it.
Can a function modify data?
Yes, a VOLATILE function may insert or update, and the changes belong to the caller's transaction, committing or rolling back with it. It still cannot commit on its own; for that we need a procedure.
How do I call these from Java?
A function is just part of a query: SELECT open_total(?) with a PreparedStatement or JdbcTemplate.queryForObject. A procedure is called with CALL, and a procedure that commits must run on a connection in autocommit mode, outside any Spring-managed transaction.
6Conclusion
In this answer, we wrote open_total as a STABLE PL/pgSQL function that sums open invoices and returns 0 instead of NULL when there are none. We saw that volatility labels tell the planner what it may cache, and that wrong labels silently give wrong results. Functions return values inside SQL and can never commit, while procedures, since PostgreSQL 11, are called with CALL, return OUT parameters and may commit when not inside an outer transaction block. Plain SQL functions can be inlined, which PL/pgSQL functions never are.
Open with
I would write it as CREATE FUNCTION open_total with a bigint parameter returning numeric, LANGUAGE plpgsql, marked STABLE, and the body returns coalesce of sum of amount from invoice where customer_id equals the parameter and status is OPEN.
Then, if they want more
The coalesce matters because sum over no rows is NULL. I name the parameter p_customer so it does not clash with the column.
STABLE tells the planner the result does not change within a statement, which is true because it only reads; IMMUTABLE would be wrong and could give stale results from cached plans or indexes, and VOLATILE would be correct but prevents optimisations. The difference from a procedure is about how they are called and transactions.
A function returns a value and is called inside SQL, like SELECT open_total(42) or in a WHERE clause, so it always runs inside the caller's transaction and can never commit or roll back.
A procedure, since PostgreSQL 11, is called with CALL, returns results through OUT parameters, and can COMMIT inside its body, for example to process a batch job in chunks, but only if CALL is not inside an explicit transaction block; from Spring that means no @Transactional and autocommit on.
I would also mention that for a one-query body like this, LANGUAGE sql is often better, because the planner can inline it, while PL/pgSQL is always a black box.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 11, PostgreSQL 14
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a PostgreSQL function in PL/pgSQL that returns the total of open invoices for a...": https://scrivio-interview-library.netlify.app/databases/stored-code/626cb0b609/