Sub topic 14
Designing transaction boundaries and avoiding pitfalls
This chapter assumes you know how COMMIT, ROLLBACK, and SAVEPOINT behave, that DDL commits implicitly, and that Oracle readers do not block writers. It covers how to decide where a transaction starts and ends, and the mistakes that come up most often in real code.
Start from the business unit of work
A transaction should match one business unit of work: a set of changes that must all succeed or all fail together. A transfer of money is the standard case. The debit and the credit belong in one transaction, because committing only one of them leaves the books wrong.
Use these questions to place a boundary:
- Would the data be inconsistent if only part of this work were saved? If so, keep it in one transaction.
- Can the work be repeated or abandoned safely after a failure? If so, it can be a separate transaction.
- Who decides when the work is final? The code that knows the whole business outcome should issue the COMMIT.
The third question matters most. A low-level procedure rarely knows whether its caller has more work to do. If it commits, it can make a half-finished unit of work permanent.
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Both updates are one unit. Nothing in this unit should commit between them.
Keep transactions short, but not too short
A transaction that stays open holds row locks, keeps undo data that other sessions' queries may need, and blocks other writers. Long transactions hurt concurrency, so avoid these habits:
- Waiting for user input between the first change and the COMMIT. A user who goes to lunch holds the locks.
- Doing slow work, such as calling a web service, in the middle of a transaction.
- Leaving a SQL*Plus or SQL Developer session open after an UPDATE without committing or rolling back.
The opposite mistake is committing too often. Splitting one unit of work into several commits breaks atomicity. It also does not help performance as much as people expect, because each commit waits for the log writer to confirm the redo is on disk.
| Approach | Benefit | Risk |
|---|---|---|
| One commit per business unit | Correct atomicity, clear failure handling | Long units hold locks longer |
| Commit after every row | Short locks | Partial results after a failure, slow, more log waits |
| One commit after millions of rows | Fewer commits | Large undo, long locks, a failure rolls back everything |
For large batch jobs, pick a middle size, such as every few thousand rows. Design the job so it can restart safely, for example by marking processed rows or recording a high-water mark in the same transaction as the work.
Common pitfalls
Committing inside a loop that is reading with a cursor
Fetching across commits is a classic problem. A cursor opened on a query keeps a read-consistent view as of the time it was opened. If the loop commits, the undo data that view needs can be reused. The session may then fail with ORA-01555: snapshot too old. Prefer a single set-based statement, or process in separate batches that each open a new cursor.
Row-by-row processing is often the root problem. One statement does the work faster and keeps it atomic:
UPDATE accounts
SET balance = balance - 100
WHERE balance >= 100;
COMMIT;If one row violates the balance check, the whole statement is rolled back, as statement-level atomicity guarantees. When you want to skip bad rows instead, use per-row savepoints as shown below.
Forgetting that DDL commits
DDL ends the current transaction. If your script inserts rows, creates a table, and then hits an error, the ROLLBACK will not undo the inserts. Keep DDL out of units of work, and run schema changes as separate, deliberate steps.
INSERT INTO accounts (id, owner, balance) VALUES (4, 'Dan', 10);
CREATE TABLE scratch_table (x NUMBER); -- commits the INSERT first
ROLLBACK; -- nothing left to undo
SELECT owner FROM accounts WHERE id = 4; -- still returns 'Dan'Relying on implicit commit at exit
A normal exit from SQLPlus commits open work, and an abnormal termination rolls it back. Do not depend on either one. Issue an explicit COMMIT or ROLLBACK so the outcome does not depend on how the session ends. In SQLPlus, SET AUTOCOMMIT OFF is the default. If a client tool or driver enables autocommit, each statement becomes its own transaction, and a multi-statement unit loses atomicity without any error message. Check the setting in your tool, JDBC connection, or ORM.
Swallowing exceptions in PL/SQL
An exception handler that catches WHEN OTHERS and does nothing hides the failure, and the caller will usually COMMIT the partial work. Either handle the exception completely, including rolling back to a known savepoint, or re-raise it.
SET SERVEROUTPUT ON
BEGIN
FOR r IN (SELECT id FROM accounts) LOOP
SAVEPOINT before_row;
BEGIN
UPDATE accounts SET balance = balance - 100 WHERE id = r.id;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO SAVEPOINT before_row;
DBMS_OUTPUT.PUT_LINE('Skipped account ' || r.id || ': ' || SQLERRM);
END;
END LOOP;
COMMIT;
END;
/This handler undoes only the failed row, reports the reason, and lets the rest continue. The decision to skip is deliberate and visible. A bare WHEN OTHERS THEN NULL is neither.
Committing inside reusable code
A procedure that commits on its own cannot take part in a larger transaction. Callers lose the ability to roll back the whole unit. A good rule is that only the outermost layer, such as the application service or the top-level batch script, issues COMMIT and ROLLBACK. Inner procedures do their work and raise exceptions.
CREATE OR REPLACE PROCEDURE debit(p_id IN NUMBER, p_amount IN NUMBER) IS
BEGIN
UPDATE accounts SET balance = balance - p_amount WHERE id = p_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'No such account: ' || p_id);
END IF;
END debit;
/The procedure has no COMMIT. The caller decides what happens next.
Using an autonomous transaction for the wrong thing
An autonomous transaction commits independently of the caller. That is the right tool for audit and error logging, where the log row should survive a rollback of the main work:
CREATE TABLE audit_log (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
msg VARCHAR2(200),
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP
);
CREATE OR REPLACE PROCEDURE log_msg(p_msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO audit_log (msg) VALUES (p_msg);
COMMIT;
END log_msg;
/It is the wrong tool for business changes. The autonomous transaction does not see the caller's uncommitted changes, and the caller cannot undo its work. If the autonomous code tries to update a row that the caller has locked, the two transactions wait on each other, and Oracle raises a deadlock error. Use autonomous transactions for logging, and nothing that must be atomic with the main work.
Check-then-act races
Reading a value and then updating based on it can fail under concurrency. Two sessions can both read a balance of 100 and both subtract 80. Under READ COMMITTED, the second UPDATE waits for the first, then proceeds on the new value. So the safest pattern is to put the condition in the statement itself:
UPDATE accounts
SET balance = balance - 80
WHERE id = 1
AND balance >= 80;If SQL%ROWCOUNT is 0, the funds were not available. When you must read first, lock the row with SELECT ... FOR UPDATE so no one else changes it before you do. Under SERIALIZABLE, a conflicting change by another committed transaction raises ORA-08177: can't serialize access for this transaction, and the application must be ready to retry the whole transaction.
Lost updates in user interfaces
An application reads a row, shows it to a user, and updates it minutes later. Another user may have changed it in the meantime. Holding a lock across the think time is too costly. Use optimistic locking instead: keep a version number or timestamp column, and include it in the UPDATE's WHERE clause. A zero row count means someone else changed the row, so reload and ask the user again.
Choosing an isolation level
| Need | Choice |
|---|---|
| Ordinary OLTP work | READ COMMITTED (default) |
| Several queries that must agree with one another, for a report | READ ONLY |
| Read and write logic that must act as if it ran alone | SERIALIZABLE, with retry on ORA-08177 |
SET TRANSACTION must be the first statement of the transaction. After a COMMIT or ROLLBACK, issue it again if you still need it.
SET TRANSACTION READ ONLY;
-- ... queries that all see the data as of the start of the transaction ...
COMMIT;Checklist for a transaction design
The diagram shows a typical layered design. Only the top layer decides the outcome.
Before you ship transaction code, check these points:
- The COMMIT is in the layer that knows the business outcome.
- Related changes are in one transaction, with no DDL in between.
- No transaction waits on a user, a network call, or a file.
- Exceptions are either fully handled or re-raised, never ignored.
- Concurrency is handled in the statement (conditional UPDATE), with a lock (
FOR UPDATE), or with a version column. - Batch jobs commit in sensible chunks and can restart.
- Autonomous transactions are limited to logging and auditing.
- Autocommit is off in every client that runs multi-statement units.
A note on distributed transactions
When one transaction changes data in more than one database through database links, Oracle coordinates the commit with two-phase commit. All sites prepare, then all commit, or all roll back. The same design rules apply, with one extra caution: a failure during the commit can leave an in-doubt transaction that an administrator must resolve. Keep distributed units small and rare.
Exercise
A procedure post_payment inserts a payment row, updates an invoice, and then calls COMMIT. A batch job calls post_payment for 500 invoices and wants to roll back everything if the 400th fails. Why can it not do that, and what is the fix?
Show answer
Each call to post_payment commits, so the first 399 payments are already permanent when the 400th fails, and ROLLBACK cannot undo them. Remove the COMMIT from post_payment so it only does its work and raises exceptions. The batch job, as the outermost layer, then issues one COMMIT after all 500 succeed, or a ROLLBACK if any call fails. If the job is too large for one transaction, commit in chunks and record progress so it can restart.
Exercise
Why is UPDATE accounts SET balance = balance - 80 WHERE id = 1 AND balance >= 80 safer than selecting the balance into a variable, checking it in PL/SQL, and then updating?
Show answer
The condition and the change happen in one statement against the current committed row. Between a separate SELECT and UPDATE, another session could change the balance, so the check could be stale. With the conditional UPDATE, a concurrent writer is made to wait, then the condition is evaluated on the new value, and SQL%ROWCOUNT shows whether the update applied.