Sub topic 15
Bulk DML errors with FORALL SAVE EXCEPTIONS
This chapter assumes you can write PL/SQL blocks with an EXCEPTION section, declare exceptions with PRAGMA EXCEPTION_INIT, and use collections. It also assumes you know how COMMIT and ROLLBACK behave. The earlier chapters on propagation and transaction control apply directly here.
The problem: one bad row stops the batch
FORALL sends a whole collection to the SQL engine in one round trip. It runs the DML statement once per element, and these runs are called iterations. This is much faster than a loop that issues one statement per row.
By default, the first failing iteration raises an exception and ends the FORALL. The failed iteration is rolled back. If you do not handle the exception, the whole FORALL is rolled back. If you do handle it, the iterations that already succeeded stay in place and the remaining ones never run. In both cases you learn only about the first error.
Often you want a different result: load every good row and get a report of the bad ones. The SAVE EXCEPTIONS clause does this.
How SAVE EXCEPTIONS works
Add SAVE EXCEPTIONS after the bounds of the FORALL. Then:
- Each iteration that fails has its error recorded, and the loop moves on to the next iteration.
- Iterations that succeed keep their changes. Nothing is rolled back for you.
- After the last iteration, if any error was recorded, PL/SQL raises ORA-24381.
- Your handler reads the recorded errors from the collection
SQL%BULK_EXCEPTIONS.
The SQL%BULK_EXCEPTIONS collection
SQL%BULK_EXCEPTIONS is a collection of records. It is only meaningful right after the FORALL that filled it, and the next FORALL replaces its contents. Each record has two fields.
| Item | Meaning |
|---|---|
| `SQL%BULK_EXCEPTIONS.COUNT` | Number of iterations that failed |
| `SQL%BULK_EXCEPTIONS(j).ERROR_INDEX` | The iteration number that failed |
| `SQL%BULK_EXCEPTIONS(j).ERROR_CODE` | The Oracle error number, stored as a positive integer |
Because ERROR_CODE is positive, negate it before passing it to SQLERRM. Using SQLERRM(SQL%BULK_EXCEPTIONS(j).ERROR_CODE) without the minus sign gives the wrong text. Oracle does not store the error message itself, so SQLERRM(-code) is how you get it back.
A complete example
This example inserts five rows. One row has a duplicate key, and another has a name that is too long for the column.
CREATE TABLE bulk_demo (
id NUMBER PRIMARY KEY,
name VARCHAR2(5) NOT NULL
);
DECLARE
TYPE t_ids IS TABLE OF NUMBER;
TYPE t_names IS TABLE OF VARCHAR2(20);
l_ids t_ids := t_ids(1, 2, 2, 4, 5);
l_names t_names := t_names('Ann', 'Bob', 'Cy', 'Dee', 'Eleanor');
e_bulk_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bulk_errors, -24381);
BEGIN
FORALL i IN 1 .. l_ids.COUNT SAVE EXCEPTIONS
INSERT INTO bulk_demo (id, name)
VALUES (l_ids(i), l_names(i));
DBMS_OUTPUT.PUT_LINE('All rows inserted');
COMMIT;
EXCEPTION
WHEN e_bulk_errors THEN
DBMS_OUTPUT.PUT_LINE('Rows inserted: ' || SQL%ROWCOUNT);
DBMS_OUTPUT.PUT_LINE('Rows failed: ' || SQL%BULK_EXCEPTIONS.COUNT);
FOR j IN 1 .. SQL%BULK_EXCEPTIONS.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(
'Iteration ' || SQL%BULK_EXCEPTIONS(j).ERROR_INDEX ||
' (id ' || l_ids(SQL%BULK_EXCEPTIONS(j).ERROR_INDEX) || '): ' ||
SQLERRM(-SQL%BULK_EXCEPTIONS(j).ERROR_CODE));
END LOOP;
COMMIT;
END;
/With SET SERVEROUTPUT ON, the output looks like this:
Rows inserted: 3
Rows failed: 2
Iteration 3 (id 2): ORA-00001: unique constraint (...) violated
Iteration 5 (id 5): ORA-12899: value too large for column ... (actual: 7, maximum: 5)Three rows are in the table: ids 1, 2 and 4. The handler uses ERROR_INDEX to look up the input element that caused each failure, so the report can name the offending data.
Three details in this example matter:
- The
COMMITafter the report is a deliberate choice.SAVE EXCEPTIONSdoes not decide whether to keep the successful rows. Your handler decides, as described below. SQL%ROWCOUNTafter aFORALLis the total number of rows affected by the iterations that succeeded.- The handler binds
e_bulk_errorsto error -24381, so it can name the error instead of testingSQLCODE.
ERROR_INDEX is an iteration number
ERROR_INDEX is the number of the iteration, counting from 1. For a dense collection that you loop over with 1 .. COUNT, the iteration number equals the subscript, so l_ids(ERROR_INDEX) works as shown above.
For a sparse collection you can loop with INDICES OF or VALUES OF. In that case the iteration number and the subscript can differ, so do not use ERROR_INDEX as a subscript without checking. If your collection can have gaps, either compact it first or keep a parallel collection that maps iteration numbers to keys.
Using 1 .. COUNT on a sparse collection fails when the loop reaches a missing element. That error is not a per-iteration DML error, so SAVE EXCEPTIONS does not capture it.
Deciding what to do with the successful rows
When the handler runs, the good rows are applied but not committed. You have three reasonable choices:
- Commit them, and report or store the failures. This suits data loads where partial success is acceptable.
- Roll back everything, and report the failures. This suits cases where the batch must be all or nothing. The example in the spine does this with
ROLLBACKin the handler. - Roll back to a savepoint that you set before the
FORALL. This keeps earlier work in the same transaction while discarding the batch.
DECLARE
TYPE t_ids IS TABLE OF NUMBER;
l_ids t_ids := t_ids(10, 20, 20);
e_bulk_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bulk_errors, -24381);
BEGIN
SAVEPOINT before_batch;
FORALL i IN 1 .. l_ids.COUNT SAVE EXCEPTIONS
INSERT INTO bulk_demo (id, name) VALUES (l_ids(i), 'Batch');
EXCEPTION
WHEN e_bulk_errors THEN
ROLLBACK TO before_batch;
DBMS_OUTPUT.PUT_LINE('Batch discarded, ' ||
SQL%BULK_EXCEPTIONS.COUNT || ' error(s)');
END;
/Here the duplicate id 20 fails at iteration 3. The handler rolls back to before_batch, which removes ids 10 and 20 as well. Anything done in the transaction before the savepoint remains pending.
Logging the failures
You can combine this chapter with the autonomous logging pattern. Call log_error once per failed iteration inside the handler. The log rows are committed independently, so a later ROLLBACK of the batch does not remove them. This gives you an audit trail even when you discard the data.
Common mistakes
- Forgetting that errors are not saved without the clause. Without
SAVE EXCEPTIONS, the first failure ends theFORALL, and you see only one error. - Omitting the handler for ORA-24381. If nothing handles it, the exception propagates to the caller. The successful rows are still pending in the transaction, which may surprise the caller.
- Not negating ERROR_CODE.
SQLERRMexpects the negative number. - Reading SQL%BULK_EXCEPTIONS too late. Another
FORALLin the handler, or in a procedure it calls, overwrites the collection. Copy what you need first. - Expecting all errors to be captured. Only errors raised by the DML statement itself, one per iteration, are saved. Problems outside the DML, such as a missing collection element, still end the statement.
Exercise
Exercise
A FORALL with SAVE EXCEPTIONS updates 1,000 rows. Iterations 10 and 500 fail. The handler for ORA-24381 prints SQL%BULK_EXCEPTIONS.COUNT and SQL%ROWCOUNT, then calls ROLLBACK. What do the two numbers show, and how many of the 1,000 updates remain in the database afterward?
Show answer
SQL%BULK_EXCEPTIONS.COUNT shows 2, the number of failed iterations. SQL%ROWCOUNT shows the rows affected by the successful iterations, which is 998 if each update touches one row. After the ROLLBACK, none of the 1,000 updates remain from this transaction, because SAVE EXCEPTIONS kept the 998 good changes pending and the ROLLBACK then discarded them.
Exercise
In the handler you write SQLERRM(SQL%BULKEXCEPTIONS(j).ERRORCODE) and get an unhelpful message. What is wrong, and what is the fix?
Show answer
ERRORCODE is stored as a positive number, but SQLERRM expects the negative Oracle error number. Use SQLERRM(-SQL%BULKEXCEPTIONS(j).ERROR_CODE).