Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a PL/SQL procedure that transfers an amount between two accounts and raises an error if the balance is too low, and show how you would call it from Java with JDBC.

The procedure locks both account rows with SELECT ... FOR UPDATE in a fixed order (lower id first) to avoid deadlocks, checks the source balance, raises RAISE_APPLICATION_ERROR(-20001, 'Insufficient funds') if it is too low, and otherwise updates both balances without committing. From Java we call it with conn.prepareCall("{call transfer(?, ?, ?)}"), set the three parameters and execute, catch the SQLException whose error code is 20001 and turn it into a domain exception, and let the Java side commit or roll back.

Why this question is asked

Money transfers are the textbook example for transactions, and many Oracle shops still keep this kind of logic in PL/SQL. A strong answer shows more than the syntax: it locks rows safely, reports business errors in a way Java can recognise, and leaves the transaction boundary to the caller. Interviewers use it to check all three. In this answer, we will recap the PL/SQL pieces we need, write the procedure, explain the lock order, call it from JDBC, map the error, and see why the procedure does not commit.

1A Quick Recap of the Pieces

A PL/SQL procedure is a named block of code stored in the database. It can take IN parameters, run SQL and contain logic. Three features matter here. SELECT ... INTO reads a value into a variable. FOR UPDATE locks the selected row, so no other transaction can change it until we finish. RAISE_APPLICATION_ERROR raises an error with our own code, which must be between -20000 and -20999, and our own message, and it reaches the client exactly like a database error.

2Writing the Procedure

Here is the procedure. It validates the input, locks both rows in a fixed order, checks the balance and moves the money.

Java
CREATE OR REPLACE PROCEDURE transfer(p_from IN NUMBER, p_to IN NUMBER, p_amt IN NUMBER) IS
v_bal accounts.balance%TYPE;
v_dummy accounts.balance%TYPE;
BEGIN
IF p_amt IS NULL OR p_amt <= 0 THEN
RAISE_APPLICATION_ERROR(-20002, 'Amount must be positive');
END IF;
IF p_from = p_to THEN
RAISE_APPLICATION_ERROR(-20003, 'Cannot transfer to the same account');
END IF;
-- lock both rows, always the lower id first
SELECT balance INTO v_dummy FROM accounts WHERE id = LEAST(p_from, p_to) FOR UPDATE;
SELECT balance INTO v_dummy FROM accounts WHERE id = GREATEST(p_from, p_to) FOR UPDATE;
SELECT balance INTO v_bal FROM accounts WHERE id = p_from; -- already locked, current value
IF v_bal < p_amt THEN
RAISE_APPLICATION_ERROR(-20001, 'Insufficient funds');
END IF;
UPDATE accounts SET balance = balance - p_amt WHERE id = p_from;
UPDATE accounts SET balance = balance + p_amt WHERE id = p_to;
-- no COMMIT: the caller decides
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20004, 'Account not found');
END transfer;
/
-- transfer(1, 2, 250) with balance 1000 -> balances 750 and +250
-- transfer(1, 2, 5000) -> ORA-20001: Insufficient funds

Notice the type anchor accounts.balance%TYPE: the variable always has the same type as the column, even if the column changes later. Notice also that the balance check happens after the lock. If we read the balance first and locked later, another transfer could spend the money between our read and our update, and the account would go negative.

3Why the Lock Order Matters

Imagine two transfers at the same time: one from account 1 to 2, the other from 2 to 1. If each locked its own source account first, the first would lock 1 and wait for 2, while the second locked 2 and waited for 1. Neither can continue. Oracle detects this deadlock and fails one of the statements with ORA-00060.

Locking in a fixed order removes the cycle. Both transfers lock account 1 first. The second one simply waits until the first commits, then proceeds. It does not matter which order we choose, only that every code path that locks accounts uses the same one.

Step throughFixed lock order: the second transfer waits instead of deadlocking
Transfer 1 -> 2Account 1Account 2Transfer 2 -> 1
lock account 1 (lower id)
lock account 1: waits
lock account 2
check balance, update both
commit releases both locks
now gets account 1, then account 2

6 messages in order. Play them, or step through them one at a time.

Both transfers start with the same row, so no cycle can form.

4Calling It From Java With JDBC

JDBC calls stored procedures through CallableStatement, using the escape syntax {call name(?, ?, ?)} that every driver understands. We control the transaction from Java: turn off auto-commit, call the procedure, then commit, or roll back if anything fails.

Java
public void transfer(long from, long to, BigDecimal amount) {
try (Connection conn = dataSource.getConnection()) {
conn.setAutoCommit(false);
try (CallableStatement cs = conn.prepareCall("{call transfer(?, ?, ?)}")) {
cs.setLong(1, from);
cs.setLong(2, to);
cs.setBigDecimal(3, amount);
cs.execute();
conn.commit(); // money moved
} catch (SQLException e) {
conn.rollback();
if (e.getErrorCode() == 20001) {
throw new InsufficientFundsException(from, amount); // domain exception
}
throw e;
}
} catch (SQLException e) {
throw new DataAccessResourceFailureException("transfer failed", e);
}
}
// transfer(1, 2, new BigDecimal("5000")) -> InsufficientFundsException

The Oracle driver reports the error number as a positive vendor code, so ORA-20001 arrives as getErrorCode() == 20001, and the message starts with ORA-20001: Insufficient funds. Matching on the code, not the message text, keeps the mapping stable if someone rewords the message. Using BigDecimal for money avoids the rounding errors of double.

In a Spring application we would usually let @Transactional manage the connection and use JdbcTemplate or SimpleJdbcCall to make the call. Spring translates SQLExceptions into its DataAccessException hierarchy, and we can register custom translations so that code 20001 becomes our own exception class; check your Spring version for the configuration details.

5Why the Procedure Does Not Commit

It is tempting to end the procedure with COMMIT. The problem is that the caller may be doing more work in the same transaction, for example writing an audit row or recording the transfer in an outbox table for other services. If the procedure commits, it commits that unrelated work too, at a moment the caller did not choose, and a later failure can no longer roll everything back together.

Leaving the commit to the caller keeps the procedure composable: it can be part of a larger unit of work, and tests can call it and roll back. The rare exception is a procedure that must record something even if the caller rolls back, such as an error log, which is what Oracle's autonomous transactions are for.

6Follow-up questions

Why not use SELECT ... FOR UPDATE NOWAIT?

NOWAIT makes the call fail immediately with ORA-00054 if the row is locked, instead of waiting. That is useful for interactive screens that should not hang, but for transfers a short wait is usually better, because the lock is held for milliseconds. FOR UPDATE WAIT 2 is a middle ground that waits up to two seconds.

Could this be done with a single UPDATE instead of a SELECT?

Yes: UPDATE accounts SET balance = balance - :amt WHERE id = :from AND balance >= :amt, then check SQL%ROWCOUNT. If it is 0, the funds were insufficient or the account is missing. This is shorter and atomic, though we still want a consistent lock order when the second update follows.

How would you test the procedure?

With an integration test against a real Oracle, for example the Oracle Free image in Testcontainers: set up two accounts, call the procedure, check balances, check that the 20001 case raises our domain exception, and run two opposite transfers concurrently to confirm there is no deadlock.

7Conclusion

In this answer, we wrote a PL/SQL transfer procedure that validates input, locks both rows with FOR UPDATE in a fixed order to prevent deadlocks, checks the balance after locking, raises RAISE_APPLICATION_ERROR(-20001) when funds are too low, and leaves the commit to the caller. From Java we called it with a CallableStatement and {call transfer(?, ?, ?)}, committed or rolled back on the Java side, and mapped error code 20001 to a domain exception.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write the procedure with three IN parameters and first validate them, so a non-positive amount or the same account on both sides raises an application error.

Then, if they want more

Then I lock both rows with SELECT FOR UPDATE, always the lower id first using LEAST and GREATEST. That fixed order matters: if one transfer goes from 1 to 2 and another from 2 to 1 and each locks its source first, they deadlock and Oracle kills one with ORA-00060. With a fixed order the second one just waits.

After locking, I read the source balance, and if it is below the amount I call RAISE_APPLICATION_ERROR with minus 20001 and Insufficient funds. Otherwise I update both balances, and I do not commit inside the procedure, because the caller might have other work in the same transaction, like an audit or outbox row.

In Java I get a connection, turn auto-commit off, and call conn.prepareCall with the call escape, braces, call transfer with three question marks. I set the long ids and a BigDecimal amount, execute, and commit. In the catch block I roll back, and if getErrorCode is 20001 I throw an InsufficientFundsException, matching on the code rather than the message. In Spring I would use @Transactional with SimpleJdbcCall and a custom exception translation.

About this answer

Last updated
12 November 2026
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 "Write a PL/SQL procedure that transfers an amount between two accounts and raises an...": https://scrivio-interview-library.netlify.app/databases/oracle-and-sql-server/e324f83eb5/