Sub topic 1
What is a transaction in Oracle?
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), can connect to an Oracle database with SQL*Plus, SQL Developer, or SQLcl, and can read simple PL/SQL blocks. Run the examples in a test schema.
What is a transaction in Oracle?
A transaction is a group of SQL statements that Oracle treats as one unit of work. It starts with the first DML statement (INSERT, UPDATE, or DELETE) after the previous transaction ended. It ends with COMMIT, ROLLBACK, a DDL statement, or a session termination.
The examples use this table:
CREATE TABLE accounts (
id NUMBER PRIMARY KEY,
owner VARCHAR2(50) NOT NULL,
balance NUMBER(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, owner, balance) VALUES (1, 'Alice', 1000);
INSERT INTO accounts (id, owner, balance) VALUES (2, 'Bob', 200);
COMMIT;ACID and how Oracle delivers it
ACID stands for atomicity, consistency, isolation, and durability.
- Atomicity: all changes in a transaction succeed, or none do.
- Consistency: constraints such as the CHECK on balance hold after each commit.
- Isolation: concurrent sessions do not see each other's uncommitted work.
- Durability: committed changes survive a crash.
Oracle provides atomicity by recording undo data for every change, so it can reverse them. It provides durability by writing redo to the log files before COMMIT returns.
Making changes permanent with COMMIT
COMMIT makes the current transaction permanent and ends it. Both sides of a transfer become visible to other sessions at the same moment:
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Until COMMIT runs, other sessions still see the old committed balances.
Undoing changes with ROLLBACK
ROLLBACK discards every uncommitted change in the current transaction and ends it:
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
ROLLBACK;
SELECT balance FROM accounts WHERE id = 1; -- returns 1000A failed statement does not end the whole transaction. Oracle undoes only that statement, and the transaction stays open until you issue COMMIT or ROLLBACK.
Exercise
Alice has 1000 and Bob has 200. You run the two transfer UPDATEs without COMMIT, and then your session terminates abnormally. What balance does another session see for Alice?
Show answer
1000. Oracle rolls back the uncommitted transfer when the session terminates, so other sessions keep seeing the last committed balance.