Sub topic 1
DML Statements and Transactions: COMMIT, ROLLBACK, SAVEPOINT
Prerequisites
You should know basic SELECT statements, WHERE clauses, and Oracle tables. You should also understand primary keys, foreign keys, and NOT NULL constraints. The examples use the emp_demo table from this tutorial.
DML, or data manipulation language, changes table data. INSERT, UPDATE, and DELETE are DML statements. MERGE can also change data. Oracle groups these changes into a transaction.
A transaction begins when your session changes data. It ends when you run COMMIT or ROLLBACK.
COMMITmakes the transaction permanent and releases its locks.ROLLBACKremoves all uncommitted changes in the transaction.SAVEPOINTmarks a position to which you can roll back without removing earlier changes.
A transaction walkthrough
Suppose you want to give Ada a raise, test another change, and then keep only the first change:
UPDATE emp_demo
SET salary = salary + 100
WHERE emp_id = 1;
SAVEPOINT after_small_raise;
UPDATE emp_demo
SET salary = salary + 500
WHERE emp_id = 1;
ROLLBACK TO SAVEPOINT after_small_raise;
COMMIT;
SELECT emp_id, salary
FROM emp_demo
WHERE emp_id = 1;The first UPDATE remains because it happened before the savepoint. The second UPDATE is undone. The COMMIT makes the first raise permanent.
A savepoint affects only the current transaction. It does not make changes visible permanently, and it does not survive a commit or a full rollback.
Choosing the transaction command
| Command | Result | Locks |
|---|---|---|
| `COMMIT` | Keeps all changes | Releases transaction locks |
| `ROLLBACK` | Removes all uncommitted changes | Releases transaction locks |
| `ROLLBACK TO SAVEPOINT name` | Removes changes after the savepoint | Releases locks acquired after that point |
Use a transaction boundary that matches the business operation. For example, an order and its order lines usually belong in one transaction. If one required step fails, roll back the whole operation rather than leaving partial data.
Important transaction behavior
Oracle keeps your uncommitted changes private from other sessions. Your session can read its own changes, but another session generally sees the earlier committed version. Your DML also places row locks so another session cannot change the same rows until you commit or roll back.
A failed DML statement normally rolls back that statement, not the entire transaction. You must decide whether to continue, use a savepoint, or roll back everything.
Most DDL statements, such as CREATE TABLE and ALTER TABLE, cause implicit commits. Avoid mixing schema changes with business-data changes in one transaction.
Exercise
You update two departments as one business operation. The second update fails, but the first update is still uncommitted. Which command removes both updates?
Show answer
ROLLBACK removes all uncommitted changes in the current transaction. Use ROLLBACK TO SAVEPOINT only when you intentionally want to keep changes made before a savepoint.