Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Show how to call a stored procedure transfer(p_from bigint, p_to bigint, p_amount numeric, OUT p_status text) from Java with plain JDBC CallableStatement and with Spring's SimpleJdbcCall. What differs between PostgreSQL and MySQL here?

With plain JDBC we call conn.prepareCall("{call transfer(?, ?, ?, ?)}"), set the inputs with setLong and setBigDecimal, register the fourth parameter with registerOutParameter(4, Types.VARCHAR), execute, and read it with getString(4). With Spring, new SimpleJdbcCall(dataSource).withProcedureName("transfer").execute(...) reads the procedure's parameter metadata and returns the OUT values in a Map. MySQL runs procedures with CALL and can return several result sets, read with getMoreResults(); the PostgreSQL driver by default turns {call} into a SELECT, which suits functions, so true procedures may need escapeSyntaxCallMode=callIfNoReturn, depending on your driver version.

Why this question is asked

Calling stored procedures from Java looks like boilerplate, but it is where many integration bugs hide: the wrong parameter index, an OUT parameter that comes back null, or a call that works on MySQL and fails on PostgreSQL with an error saying the procedure is not a function. Interviewers ask this to check that we can write the JDBC code correctly, know what Spring adds, and understand the driver differences. In this answer, we will create the procedure, call it with CallableStatement, then with SimpleJdbcCall, go through the PostgreSQL and MySQL differences, and finish with transactions and error handling.

1The Procedure We Will Call

Here is a PostgreSQL version of transfer. It moves an amount between two accounts and reports the outcome through an OUT parameter. Procedures with OUT parameters are supported since PostgreSQL 14; earlier versions only allowed INOUT.

SQL
CREATE PROCEDURE transfer(p_from bigint, p_to bigint, p_amount numeric, OUT p_status text)
LANGUAGE plpgsql AS $$
BEGIN
UPDATE account SET balance = balance - p_amount
WHERE id = p_from AND balance >= p_amount;
IF NOT FOUND THEN
p_status := 'INSUFFICIENT_FUNDS';
RETURN;
END IF;
UPDATE account SET balance = balance + p_amount WHERE id = p_to;
p_status := 'OK';
END $$;
CALL transfer(1, 2, 25.00, NULL); -- p_status = OK (NULL is the placeholder for the OUT parameter)

2Calling It With CallableStatement

CallableStatement is the JDBC interface for calling stored code. We write the call in JDBC's escape syntax, {call name(?, ?, ...)}, which the driver translates into its database's native syntax. Each ? is a parameter, numbered from 1. Input parameters are set like those of a PreparedStatement; output parameters must be registered with their SQL type before executing, so the driver knows what to expect.

Java
try (Connection conn = dataSource.getConnection();
CallableStatement cs = conn.prepareCall("{call transfer(?, ?, ?, ?)}")) {
cs.setLong(1, 1L); // p_from
cs.setLong(2, 2L); // p_to
cs.setBigDecimal(3, new BigDecimal("25.00")); // p_amount: never a double for money
cs.registerOutParameter(4, Types.VARCHAR); // p_status
cs.execute();
String status = cs.getString(4); // "OK"
}

Notice that the OUT value is read from the statement after execute(), by the same index we registered. BigDecimal keeps the exact amount; a double would turn 0.1 into 0.1000000000000000055 before it ever reached the database.

3Calling It With SimpleJdbcCall

Spring's SimpleJdbcCall removes most of that code. We give it the procedure's name, and on first use it reads the procedure's parameters from the driver's database metadata (DatabaseMetaData.getProcedureColumns), so it knows the names, types and directions. We then pass input values by parameter name, and it returns a Map with the OUT values. The object is thread-safe after it is compiled, so we create it once, for example in a repository's constructor.

Java
@Repository
class TransferDao {
private final SimpleJdbcCall transferCall;
TransferDao(DataSource ds) {
this.transferCall = new SimpleJdbcCall(ds).withProcedureName("transfer");
}
String transfer(long from, long to, BigDecimal amount) {
Map<String, Object> out = transferCall.execute(Map.of(
"p_from", from, "p_to", to, "p_amount", amount));
return (String) out.get("p_status"); // "OK"
}
}

The keys in the returned map are the parameter names as the metadata reports them, which may be lower case or upper case depending on the database and driver, so check them once in a test. When metadata lookup is unreliable, for example with a driver that reports procedures and functions differently, we can switch it off with withoutProcedureColumnMetaDataAccess() and declare the parameters ourselves with declareParameters(new SqlParameter("p_from", Types.BIGINT), ..., new SqlOutParameter("p_status", Types.VARCHAR)).

4PostgreSQL and MySQL Differences

In MySQL, procedures have always been called with CALL, and Connector/J translates the escape syntax to CALL transfer(?, ?, ?, ?) directly, so the code above works as written. MySQL procedures can also return result sets from SELECT statements inside them, and a single call can return several. We read them in order: execute() returns true if the first result is a result set, and getMoreResults() moves to the next one.

In PostgreSQL, functions came long before procedures, and the PostgreSQL JDBC driver historically translated {call f(?)} into a SELECT * FROM f(?) query, which is how functions are called. A true procedure cannot be called with SELECT, so with the default setting the call fails with an error saying that transfer is a procedure and should be called with CALL. The driver's escapeSyntaxCallMode connection property controls this: select (the default) always uses SELECT, callIfNoReturn uses CALL when no return value is registered with the {? = call ...} form, and call always uses CALL. For procedures with OUT parameters, how the driver binds the OUT placeholder has changed across versions, so check your driver version and test the call.

Java
# PostgreSQL JDBC URL for procedure calls
jdbc:postgresql://db:5432/bank?escapeSyntaxCallMode=callIfNoReturn
// MySQL: a procedure that returns two result sets
try (CallableStatement cs = conn.prepareCall("{call account_report(?)}")) {
cs.setLong(1, 1L);
boolean isResultSet = cs.execute();
while (true) {
if (isResultSet) {
try (ResultSet rs = cs.getResultSet()) { while (rs.next()) { /* read rows */ } }
} else if (cs.getUpdateCount() == -1) {
break; // no more results
}
isResultSet = cs.getMoreResults();
}
}
The same call on two databases
PostgreSQLMySQL
Native syntaxCALL for procedures, SELECT for functionsCALL
Driver default for {call ...}translated to SELECTtranslated to CALL
Setting for proceduresescapeSyntaxCallMode=callIfNoReturn or callnone needed
Result sets from the callusually a refcursor OUT, or a functionseveral, via getMoreResults()
OUT parametersprocedures since PostgreSQL 14yes
The Java code is the same; the driver settings and result handling differ.

5Transactions and Error Handling

The call runs inside whatever transaction the connection is in. In a Spring @Transactional method, the procedure's updates commit or roll back with the rest of the method, which is usually what we want for a transfer. A PostgreSQL procedure that issues COMMIT itself cannot run inside such a transaction, so we keep transaction control in one place, normally in Java.

Errors arrive as SQLException, which Spring translates into its DataAccessException hierarchy. We map the ones that matter to meaningful results: a business outcome such as insufficient funds is better returned through the status parameter, as here, or raised from the procedure with a specific SQLSTATE that the Java code recognises, than surfaced as a generic 500 error.

6Follow-up questions

How do you read a result set returned as a refcursor in PostgreSQL?

A function or procedure can return a refcursor, a named cursor over a query's result. The cursor only exists inside the transaction, so autocommit must be off: we call it with conn.setAutoCommit(false), register the OUT parameter as Types.REF_CURSOR (older drivers use Types.OTHER), execute, and read it with cs.getObject(1, ResultSet.class) or getObject(1) cast to ResultSet. We then iterate the rows before the transaction commits, because committing closes the cursor.

Why use SimpleJdbcCall instead of JdbcTemplate.call?

SimpleJdbcCall reads the parameter metadata and lets us pass values by name, so the code does not depend on parameter positions. JdbcTemplate.call with a CallableStatementCreator gives full control but needs the same boilerplate as plain JDBC. For a function that returns a single value, a plain JdbcTemplate.queryForObject("select f(?)", ...) is often simplest.

Does the order of setting parameters matter?

No, but the indexes do: each index must match the position in the call string. Registering an OUT parameter with the wrong type or index usually causes a conversion error or a null value, which is a good reason to use named parameters through SimpleJdbcCall where possible.

7Conclusion

In this answer, we called a transfer procedure with an OUT status parameter in two ways. With JDBC we used prepareCall with the escape syntax, set inputs with setLong and setBigDecimal, registered the OUT parameter as VARCHAR, executed and read it with getString(4). With Spring we used SimpleJdbcCall, which reads parameter metadata and returns OUT values in a Map. MySQL calls procedures with CALL and can return multiple result sets read with getMoreResults(), while the PostgreSQL driver translates {call} to SELECT by default, so procedures need escapeSyntaxCallMode. The call joins the current transaction, and errors should be mapped to meaningful results.

What to say in the interviewAbout 90 seconds aloud

Open with

With plain JDBC, I would use conn.prepareCall with the escape syntax, curly brace call transfer with four question marks. I set the inputs by position, setLong for the two account ids and setBigDecimal for the amount, never a double for money, then registerOutParameter on index 4 with Types.VARCHAR, call execute, and read the status with getString(4).

Then, if they want more

With Spring I would create a SimpleJdbcCall once with withProcedureName transfer. On first use it reads the parameter metadata from the driver, so I just pass a map of input names to values and get back a map with p_status. If the metadata is unreliable I can turn it off and declare SqlParameter and SqlOutParameter myself.

The differences are mostly in the drivers. MySQL has always used CALL, Connector/J translates the escape syntax to CALL, and a procedure can return several result sets, which I loop over with getResultSet and getMoreResults.

PostgreSQL had functions long before procedures, and its JDBC driver translates the call escape into SELECT by default, which fails for a real procedure, so I set escapeSyntaxCallMode to callIfNoReturn or call in the URL and test the OUT parameter handling for my driver version.

In both cases the call runs in the current transaction, so in a @Transactional method it commits with the rest, and I map SQLExceptions or a status value to meaningful errors.

About this answer

Last updated
12 November 2026
Versions it names
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.
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 "Show how to call a stored procedure transfer(p_from bigint, p_to bigint, p_amount...": https://scrivio-interview-library.netlify.app/databases/stored-code/5e4923715c/