Sub topic 3
Making changes permanent with COMMIT
This chapter covers what COMMIT does, what it guarantees, what other sessions see before and after it, and the commit variants you will meet in practice. It assumes you can run SELECT, INSERT, UPDATE, and DELETE, and that you can connect to an Oracle database with SQL*Plus, SQL Developer, or SQLcl. The examples use the accounts table from the earlier chapters.
What COMMIT does
A transaction is a sequence of SQL statements that Oracle treats as one unit of work. COMMIT ends the current transaction and makes all of its changes permanent. It also makes those changes visible to other sessions, and it releases the row locks the transaction holds.
After a successful COMMIT:
- The changes are stored durably. They survive a session crash, an instance crash, and a power loss.
- Other sessions that start a query afterwards see the new data.
- Row locks held by the transaction are released, so sessions waiting on those rows can continue.
- Any savepoints in the transaction are erased.
- The next DML statement (INSERT, UPDATE, DELETE, MERGE) starts a new transaction.
Here is the transfer from the earlier chapter, with a check before and after:
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
SELECT id, balance FROM accounts WHERE id IN (1, 2) ORDER BY id;
COMMIT;The SELECT inside the transaction shows your own uncommitted changes. Other sessions still see the old balances until you issue COMMIT. The two updates become visible to everyone at the same moment. No other session can see only half of the transfer.
The commit point
Oracle treats a transaction as committed at one instant, called the commit point. At that instant Oracle assigns the transaction a system change number (SCN), a number that increases with every commit and orders all changes in the database.
A transaction is committed when the log writer process (LGWR) has written the transaction's commit record to the online redo log. Writing the changed data blocks to the data files is not part of the commit. The database writer (DBWR) does that later, in the background. If the instance crashes before the data files are updated, Oracle replays the redo log during recovery and the committed work is restored.
This design keeps commits fast. A commit needs one sequential write to the redo log. It does not need many random writes to data files. It also means the cost of a commit does not depend on how many rows you changed. Committing one million rows costs about the same as committing one row, apart from the volume of redo already generated.
The next diagram shows the order of events.
The session does not get "Commit complete" until the redo write finishes. This is the default behavior, and the section on COMMIT options below shows how to change it.
Explicit and implicit commits
An explicit commit is a COMMIT statement you write. An implicit commit happens without one. Later chapters cover implicit commits in detail, but you need the short version here:
- DDL statements such as CREATE, ALTER, DROP, and TRUNCATE commit the open transaction before and after they run.
- A normal exit from SQLPlus, SQLcl, or a similar client commits by default in SQLPlus (depending on the
EXITCOMMITsetting). - An abnormal termination, such as a killed session or a lost connection, rolls back the open transaction.
Because of the DDL rule, a COMMIT is sometimes redundant:
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'Do not rely on implicit commits for correctness. Writing COMMIT where you mean to commit makes the intent visible to the next reader.
Checking whether a transaction is open
Oracle does not tell you at the prompt whether you have uncommitted work. You can check from another query by looking at the V$TRANSACTION view. It lists active transactions, and your session's entry is found by joining on the session address:
SELECT t.xidusn, t.xidslot, t.xidsqn, t.start_time, t.used_urec
FROM v$transaction t
JOIN v$session s ON s.taddr = t.addr
WHERE s.sid = SYS_CONTEXT('USERENV', 'SID');If the query returns a row, your session has an open transaction. If it returns no rows, there is none. Querying these views requires the SELECT privilege on V$TRANSACTION and V$SESSION, which ordinary users usually lack, so you may need a DBA to grant it. A plain SELECT does not start a transaction, so this check returns nothing in a session that has only run queries.
Committing and constraints
Constraints are checked as part of statement execution, so a statement that violates the CHECK (balance >= 0) rule fails immediately and is rolled back on its own. Deferrable constraints are the exception. If a constraint is declared DEFERRABLE INITIALLY DEFERRED, Oracle checks it at COMMIT time instead:
CREATE TABLE ledger (
id NUMBER PRIMARY KEY,
amount NUMBER NOT NULL,
CONSTRAINT ledger_positive CHECK (amount > 0)
DEFERRABLE INITIALLY DEFERRED
);
INSERT INTO ledger (id, amount) VALUES (1, -5); -- succeeds for now
COMMIT;The COMMIT fails with ORA-02091: transaction rolled back and an ORA-02290 message naming the violated constraint. The whole transaction is rolled back, not just the offending row. This is the one case where COMMIT itself can fail because of your data. Use deferred constraints deliberately, for example to load rows in any order into tables that reference each other.
COMMIT options
By default, COMMIT waits until LGWR has written the commit record to disk. You can change that with the WRITE clause:
COMMIT WRITE IMMEDIATE WAIT; -- the default behavior
COMMIT WRITE BATCH NOWAIT; -- fastest, least durableThe clause has two independent parts:
| Option | Meaning |
|---|---|
| `IMMEDIATE` | LGWR is asked to write right now. |
| `BATCH` | LGWR may buffer the write and combine it with others. |
| `WAIT` | COMMIT returns only after the redo is written. |
| `NOWAIT` | COMMIT returns at once, without waiting for the write. |
With NOWAIT, your session may be told the commit succeeded before the redo has reached disk. If the instance fails in that short window, the transaction is lost even though your application believed it committed. This trade-off is acceptable for data you can regenerate, such as a staging load that can be rerun. It is a poor choice for payments or any record you cannot recreate. The same behavior can be set for a whole session or instance with the COMMIT_WRITE initialization parameter, but an explicit clause on the statement is clearer. A later chapter returns to this topic.
Commit frequency
How often you commit is a design decision. Two opposite mistakes are common.
Committing too rarely holds locks and undo for a long time. Other sessions wait on your locked rows, and a very large transaction can run out of undo space.
Committing too often inside a loop slows the work, because each commit waits for a redo write. It also breaks atomicity. If a job processes 10,000 rows and commits after each one, a failure at row 5,000 leaves the first 4,999 changes permanent and the rest undone, with no simple way to return to the starting state.
BEGIN
FOR r IN (SELECT id FROM accounts) LOOP
UPDATE accounts SET balance = balance + 1 WHERE id = r.id;
COMMIT; -- avoid: one commit per row
END LOOP;
END;
/A better version does the work in one statement and commits once:
UPDATE accounts SET balance = balance + 1;
COMMIT;There is a second reason to avoid commit inside a cursor loop that is reading from the table being changed. Committing ends the transaction, and a loop that uses SELECT ... FOR UPDATE loses its row locks at the commit. A later fetch from that cursor can then raise ORA-01002: fetch out of sequence. Commit after the loop, not inside it.
The rule is to commit when a business unit of work is complete, no earlier and no later. A transfer is one unit, so both updates commit together.
Common errors and pitfalls
- Forgetting to commit. Your own session sees the data, but other sessions do not, and the locks remain. This is the most frequent cause of "my change is missing" reports and of sessions blocked on a row.
- Assuming COMMIT can be undone. After COMMIT, ROLLBACK has nothing to undo. Recovering committed data needs other tools, such as Flashback Query.
- Committing inside reusable code. A procedure that calls COMMIT takes away the caller's ability to roll back. Leave the commit to the code that owns the whole unit of work.
- Relying on exit behavior. Whether a clean exit commits depends on the client and its settings. Commit explicitly before you leave.
- Using a deferred constraint and expecting an early error. The failure appears at COMMIT and rolls back everything.
Summary
COMMIT ends a transaction, makes its changes permanent and visible, and releases its locks. The commit point is the redo write by LGWR, which is why commits are fast and why committed data survives crashes. DDL commits implicitly, but explicit commits state your intent. Deferred constraints are checked at COMMIT and can make it fail. The WRITE clause trades durability for speed. Choose commit points that match whole business units of work.
Exercise
A session runs UPDATE accounts SET balance = balance - 100 WHERE id = 1; and then, without committing, a second session queries the same row. What balance does the second session see, and when does it see the new value? What happens if the first session then runs COMMIT WRITE BATCH NOWAIT and the instance crashes a moment later?
Show answer
The second session sees the old, committed balance, because Oracle shows other sessions only committed data. It sees the new balance in any query that starts after the first session commits. With COMMIT WRITE BATCH NOWAIT, the COMMIT returns before LGWR has necessarily written the redo, so if the instance crashes in that short window the update can be lost even though the application was told the commit succeeded. With the default WAIT behavior, the commit would have been durable before it returned.
Exercise
A table has the constraint CHECK (amount > 0) DEFERRABLE INITIALLY DEFERRED. You insert one valid row and one row with amount -5, then run COMMIT. What happens to the valid row?
Show answer
The COMMIT fails because the deferred constraint is checked at commit time, and Oracle rolls back the entire transaction. The valid row is rolled back too, and the error is ORA-02091 together with ORA-02290 naming the constraint.