Sub topic 1
DML statements and transactions: COMMIT, ROLLBACK, SAVEPOINT
Prerequisites
This chapter assumes you can write SELECT with a WHERE clause, that you know the Oracle types NUMBER, VARCHAR2, and DATE, and that you understand primary key, foreign key, and NOT NULL constraints. You should be able to run SQL in SQL*Plus, SQL Developer, or SQLcl.
Setting up the example tables
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_archive AS SELECT * FROM emp_demo WHERE 1 = 0;Transactions: COMMIT, ROLLBACK, and SAVEPOINT
DML (data manipulation language) statements are INSERT, UPDATE, DELETE, and MERGE. A transaction is the set of DML changes made since the last COMMIT or ROLLBACK. Your session sees its own uncommitted changes. Other sessions do not see them until you commit.
- COMMIT makes the transaction permanent.
- ROLLBACK undoes all uncommitted changes.
- SAVEPOINT marks a point that you can roll back to without undoing the whole transaction.
INSERT INTO dept_demo (dept_id, dept_name) VALUES (10, 'Sales');
SAVEPOINT after_sales;
INSERT INTO dept_demo (dept_id, dept_name) VALUES (20, 'Engineering');
ROLLBACK TO SAVEPOINT after_sales;
COMMIT;After this block, the Sales row is saved and the Engineering row is not.
Adding rows with INSERT ... VALUES
Name the columns in the column list. A column you omit takes its DEFAULT value, or NULL if it has no default.
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary)
VALUES (1, 'Ada', 10, 9000);
INSERT INTO emp_demo (emp_id, emp_name, dept_id, salary, status)
VALUES (2, 'Grace', 10, 7000, 'INACTIVE');
COMMIT;Ada's status is 'ACTIVE' because the column default applies.
| Error | Meaning | Typical cause |
|---|---|---|
| ORA-00001 | Unique or primary key constraint violated | Reusing an existing emp_id |
| ORA-02291 | Parent key not found | dept_id that does not exist in dept_demo |
| ORA-01400 | Cannot insert NULL | Omitting emp_name |
Copying rows with INSERT ... SELECT
INSERT ... SELECT inserts the rows that a query returns. The select list must match the column list in number and type.
INSERT INTO emp_archive (emp_id, emp_name, dept_id, salary, status)
SELECT emp_id, emp_name, dept_id, salary, status
FROM emp_demo
WHERE status = 'INACTIVE';
COMMIT;Changing rows with UPDATE
An UPDATE without a WHERE clause changes every row in the table. Always check the WHERE clause first.
UPDATE emp_demo
SET salary = salary * 1.05
WHERE dept_id = 10;
COMMIT;Exercise
You insert a row into emp_demo, run ROLLBACK, and then query the table from another session. What does the other session see?
Show answer
The other session sees no row. ROLLBACK undid the uncommitted insert, and other sessions never saw the row before the commit.