Sub topic 1
DML Statements and Transactions: COMMIT, ROLLBACK, SAVEPOINT
Prerequisites
This chapter assumes you can already do the following:
- Write basic
SELECTqueries withWHEREclauses. - Read table definitions that use
NUMBER,VARCHAR2, andDATEcolumns. - Recognize primary key, foreign key, and
NOT NULLconstraints. - Run SQL in SQL*Plus, SQL Developer, or SQLcl.
You do not need to know INSERT, UPDATE, DELETE, or MERGE yet. Later chapters cover each one in detail. This chapter explains the transaction model they all share.
What DML is
Data Manipulation Language (DML) is the group of SQL statements that change the rows in a table. Oracle has four of them:
| Statement | What it does |
|---|---|
| `INSERT` | Adds new rows |
| `UPDATE` | Changes column values in existing rows |
| `DELETE` | Removes rows |
| `MERGE` | Updates, inserts, and optionally deletes rows in one statement |
SELECT is not DML in this sense, because it does not change data. Data Definition Language (DDL), such as CREATE TABLE or TRUNCATE, changes the structure of the database. DDL behaves differently with transactions, as you will see below.
Demo tables used in this tutorial
The examples use four small tables, so you do not need a sample schema. Run this script once.
CREATE TABLE dept_demo (
dept_id NUMBER PRIMARY KEY,
dept_name VARCHAR2(50) NOT NULL
);
CREATE TABLE emp_demo (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50) NOT NULL,
dept_id NUMBER REFERENCES dept_demo (dept_id),
salary NUMBER(8,2),
status VARCHAR2(10) DEFAULT 'ACTIVE' NOT NULL
);
CREATE TABLE emp_stage AS SELECT * FROM emp_demo WHERE 1 = 0;
CREATE TABLE emp_archive AS SELECT * FROM emp_demo WHERE 1 = 0;emp_stage and emp_archive start empty. WHERE 1 = 0 is never true, so CREATE TABLE ... AS SELECT copies the column layout but no rows. It does not copy the primary key or foreign key constraints. It does keep NOT NULL constraints and the DEFAULT value.
Now add some data.
INSERT INTO dept_demo (dept_id, dept_name) VALUES (10, 'Sales');
INSERT INTO dept_demo (dept_id, dept_name) VALUES (20, 'Engineering');
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (1, 'Ada', 20, 9000);
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
VALUES (2, 'Grace', 10, 7000, 'INACTIVE');
COMMIT;Each statement names its columns. Ada's row leaves out status, so Oracle fills in the default 'ACTIVE'. The last line, COMMIT, is the subject of the rest of this chapter.
What a transaction is
A transaction is a sequence of statements that Oracle treats as one unit of work. Either all of its changes become permanent, or none of them do. A classic example is moving money between two accounts. Two UPDATE statements must succeed together, or the books will not balance.
Oracle transactions have these properties:
- A transaction starts implicitly with your first DML statement after connecting, or after the previous transaction ended. There is no
BEGIN TRANSACTIONstatement in Oracle SQL. - It ends when you issue
COMMITorROLLBACK, run a DDL statement, or disconnect. - Until it ends, your changes are visible only to your own session.
The last point matters most. Other sessions keep seeing the data as it was before your change. Oracle reconstructs that older view from undo data, a store of the previous values of changed rows. This is called read consistency.
COMMIT
COMMIT ends the transaction and makes every change in it permanent. After it returns, the changes are visible to all sessions and survive a crash, because Oracle has written the redo information to disk.
UPDATE emp_demo SET salary = 9500 WHERE emp_id = 1;
COMMIT;Two things are worth knowing about commits:
- A commit releases all row locks your transaction holds. Other sessions that were waiting on those rows can then continue.
- Committing is not free. Committing after every row in a large load is slow, and it also destroys your ability to undo the load as a whole. Commit when a logical unit of work is complete, not on a fixed row count by habit.
Implicit commits
Oracle commits automatically in some situations, and this surprises many people.
- Any DDL statement (
CREATE,ALTER,DROP,TRUNCATE) commits the current transaction before it runs and again after it finishes. Even a DDL statement that fails can leave your earlier DML committed. - A normal exit from SQLPlus or SQLcl commits by default. This is controlled by the
EXITCOMMITsetting in SQLPlus, which defaults toON. - If a session ends abnormally, for example when the network drops, Oracle rolls back the uncommitted work.
Some tools also offer an autocommit option. SQL*Plus has SET AUTOCOMMIT ON, and many GUI tools turn it on by default. With autocommit on, each DML statement commits as soon as it finishes, so ROLLBACK has nothing to undo. Check your tool's setting before you run anything you might want to take back.
ROLLBACK
ROLLBACK ends the transaction and discards every uncommitted change in it. The rows return to the values they had at the start of the transaction, and the locks are released.
DELETE FROM emp_demo WHERE dept_id = 10;
SELECT COUNT(*) FROM emp_demo WHERE dept_id = 10; -- 0 in your session
ROLLBACK;
SELECT COUNT(*) FROM emp_demo WHERE dept_id = 10; -- 1 againBetween the DELETE and the ROLLBACK, only your session sees the missing row. This makes a transaction a safe place to experiment, as long as you remember to look at the result before you commit.
Statement-level rollback
Rollback also happens on a smaller scale. If a single DML statement fails partway through, Oracle undoes that statement's partial changes automatically. Earlier statements in the same transaction stay intact and remain uncommitted. For example, an UPDATE that changes 500 rows and fails on row 501 with a constraint error leaves no rows changed by that statement. You then decide whether to fix the problem and continue, or to roll back the whole transaction.
SAVEPOINT and ROLLBACK TO SAVEPOINT
A savepoint is a named marker inside a transaction. You can roll back to the marker and undo only the work done after it. The work before the marker stays in the transaction, still uncommitted.
SAVEPOINT before_raise;
UPDATE emp_demo SET salary = salary + 500 WHERE dept_id = 20;
ROLLBACK TO SAVEPOINT before_raise;
COMMIT;The raise is undone. Anything done before SAVEPOINT before_raise is still part of the transaction, and the final COMMIT makes it permanent.
Rules for savepoints:
- Savepoint names are scoped to the transaction. A
COMMITor fullROLLBACKerases them all. - Rolling back to a savepoint erases any savepoints created after it. The savepoint you rolled back to stays, so you can roll back to it again.
- Reusing a savepoint name moves the marker to the new position. The earlier marker with that name is lost.
- Rolling back to a savepoint releases the row locks acquired after the savepoint. Locks acquired before it stay.
ROLLBACK TO SAVEPOINTdoes not end the transaction. You must stillCOMMITorROLLBACK.
A worked sequence shows the rules together.
INSERT INTO dept_demo (dept_id, dept_name) VALUES (30, 'Support');
SAVEPOINT after_dept;
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (3, 'Linus', 30, 6000);
SAVEPOINT after_emp;
DELETE FROM emp_demo WHERE emp_id = 2;
ROLLBACK TO SAVEPOINT after_emp; -- undoes only the DELETE
ROLLBACK TO SAVEPOINT after_dept; -- undoes the INSERT of Linus; after_emp is gone
COMMIT; -- the Support department is committedAfter this script, dept_demo contains department 30, and emp_demo is unchanged. Trying ROLLBACK TO SAVEPOINT after_emp after the second rollback would raise ORA-01086: savepoint 'AFTER_EMP' never established in this session or is invalid.
When savepoints help
Savepoints are useful when a program does a series of steps and one step is allowed to fail. The program sets a savepoint, tries the risky step, and rolls back to the savepoint on failure. The rest of the transaction continues. In PL/SQL, this pairs naturally with exception handlers.
BEGIN
INSERT INTO dept_demo (dept_id, dept_name) VALUES (40, 'Legal');
SAVEPOINT before_risky;
BEGIN
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (1, 'Duplicate', 40, 5000); -- emp_id 1 already exists
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
ROLLBACK TO SAVEPOINT before_risky;
DBMS_OUTPUT.PUT_LINE('Skipped duplicate employee');
END;
COMMIT;
END;
/The duplicate insert raises ORA-00001, which PL/SQL maps to DUP_VAL_ON_INDEX. The handler rolls back to the savepoint, and the Legal department is still committed. Strictly, the failed statement was already undone by statement-level rollback, so the savepoint is not required here. It becomes important when the risky step is several statements long.
Seeing your own uncommitted changes from another session
You can check the visibility rules yourself with two sessions, A and B.
- In session A, run
UPDATE emp_demo SET salary = 1 WHERE emp_id = 1;and do not commit. - In session A, run
SELECT salary FROM emp_demo WHERE emp_id = 1;. It returns1. - In session B, run the same
SELECT. It returns the old salary, because B reads the committed version. - In session B, try
UPDATE emp_demo SET salary = 2 WHERE emp_id = 1;. It waits, because A holds the row lock. - In session A, run
ROLLBACK;. Session B's update then proceeds.
Readers do not block writers in Oracle, and writers do not block readers. Writers do block other writers on the same row. A later chapter covers row locks in more depth.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Leaving a session open without committing | Other sessions wait on your row locks | Commit or roll back promptly |
| Assuming a DDL statement can be rolled back | Earlier DML was already committed | Keep DDL outside your DML unit of work |
| Running DML with autocommit on | `ROLLBACK` cannot undo anything | Turn autocommit off before risky changes |
| Committing inside a loop for every row | Slow, and a failed load cannot be undone as a whole | Commit once per logical unit |
| Running `UPDATE` or `DELETE` without `WHERE` | Every row is changed | Run the matching `SELECT` first and check the count |
Summary
- DML changes rows, and every DML statement runs inside a transaction.
- A transaction starts with your first DML statement and ends with
COMMIT,ROLLBACK, DDL, or disconnect. COMMITmakes changes permanent and visible to others, and releases locks.ROLLBACKdiscards all uncommitted work.SAVEPOINTlets you undo part of a transaction without ending it.- A failed statement rolls back by itself, but the rest of the transaction survives.
Exercise
Session A runs INSERT INTO dept_demo (dept_id, dept_name) VALUES (50, 'Ops');, then SAVEPOINT s1;, then INSERT INTO dept_demo (dept_id, dept_name) VALUES (60, 'HR');, then ROLLBACK TO SAVEPOINT s1;, then COMMIT;. Which departments exist afterwards, and which ones can session B see?
Show answer
Department 50 (Ops) exists and is committed. Department 60 (HR) was undone by the rollback to s1. Once the commit finishes, session B can see department 50. Before the commit, B could not see either row.
Exercise
You run UPDATE emp_demo SET salary = 1;, then CREATE TABLE tmp_check (n NUMBER);, then ROLLBACK;. What is the salary of each employee, and why?
Show answer
Every salary is 1. The CREATE TABLE statement is DDL, so Oracle committed the open transaction, including the update, before and after it ran. The ROLLBACK then had nothing to undo.
Exercise
A transaction creates savepoint a, then savepoint b, then rolls back to a. Can it now run ROLLBACK TO SAVEPOINT b? Why or why not?
Show answer
No. Rolling back to a erases savepoints created after it, so b no longer exists. Oracle raises ORA-01086. Savepoint a still exists and can be used again.