PL/SQL is a real programming language inside the database, and the single most important performance concept in it is the context switch between the PL/SQL engine and the SQL engine. A loop that executes one INSERT per iteration pays that switch every time. BULK COLLECT and FORALL batch the work and routinely give a tenfold improvement or better - this is the first thing to check in any slow PL/SQL.
Packages are the unit of organisation: a specification declaring the public interface and a body holding the implementation. Granting EXECUTE on a package without granting any table privilege gives you a genuinely narrow interface, and the package's state persists for a session.
Exception handling. Named exceptions (NO_DATA_FOUND, TOO_MANY_ROWS, DUP_VAL_ON_INDEX) plus WHEN OTHERS. The rule that matters: WHEN OTHERS THEN NULL is the worst line in PL/SQL - it swallows every error silently and is responsible for an enormous amount of undiagnosable behaviour in production systems. If you catch OTHERS, log it and re-raise with RAISE or RAISE_APPLICATION_ERROR. Capture DBMS_UTILITY.FORMAT_ERROR_BACKTRACE to keep the line number.
Read consistency is built on undo, not locks. When a row is modified, the previous version is written to the undo tablespace. A query that started before the change reads the old version from undo, reconstructing the block as it was at the query's start. The consequences are the ones Oracle is known for: readers never block writers and writers never block readers, and a long query returns results consistent with its start time, not a smear across its runtime.
The failure mode is ORA-01555: snapshot too old: a long-running query needs an undo version that has been overwritten because undo retention was too short or the undo tablespace too small for the write volume. It is not a corruption; it is a capacity planning signal.
Locks. Oracle locks rows, not pages, and never escalates to a table lock - a genuine architectural advantage. SELECT ... FOR UPDATE locks explicitly, with NOWAIT or WAIT n to control the wait. ORA-00054 is "resource busy with NOWAIT specified". Deadlocks produce ORA-00060, Oracle rolls back one statement (not the whole transaction) and writes a trace file.
Laboratory exercise 3 - a service under concurrency.
Build a PL/SQL package implementing order placement, and a client service that calls it. Run at least 50 concurrent clients.
Demonstrate the bulk operations difference: write a loop inserting 100,000 rows one at a time, then the same with FORALL, and measure both. Report the ratio.
Demonstrate read consistency: start a long-running query, modify the underlying data from another session and commit, and show the query returning the original values. Then force ORA-01555 by shrinking undo retention and repeating with a longer query.
Produce a deadlock with two sessions locking in opposite orders, capture ORA-00060, find the trace file, and fix it by ordering.
Finally, write a procedure with WHEN OTHERS THEN NULL, show a failure vanishing, then replace it with correct handling and show the backtrace.
Deliverable: the package, the load script, the bulk-versus-row-by-row measurements, the read-consistency and ORA-01555 demonstrations, the deadlock trace, and the before-and-after error handling.
-- ------------------------------------------------------------------
-- A package: specification, then body.
-- ------------------------------------------------------------------
CREATE OR REPLACE PACKAGE ord_owner.order_api AS
e_insufficient_credit EXCEPTION;
PRAGMA EXCEPTION_INIT(e_insufficient_credit, -20001);
FUNCTION place_order(p_customer_id NUMBER, p_product_id NUMBER,
p_quantity NUMBER) RETURN NUMBER;
PROCEDURE load_lines(p_order_id NUMBER);
END order_api;
/
CREATE OR REPLACE PACKAGE BODY ord_owner.order_api AS
FUNCTION place_order(p_customer_id NUMBER, p_product_id NUMBER,
p_quantity NUMBER) RETURN NUMBER
IS
v_order_id NUMBER;
v_price NUMBER(19,4);
v_credit NUMBER(19,4);
BEGIN
-- FOR UPDATE: lock the row now rather than upgrading later.
-- Oracle locks ROWS and never escalates to a table lock.
SELECT credit_limit INTO v_credit
FROM ord_owner.customer
WHERE customer_id = p_customer_id
FOR UPDATE WAIT 5; -- NOWAIT -> ORA-00054 immediately
-- WAIT 5 -> ORA-30006 after 5 seconds
SELECT list_price INTO v_price
FROM ord_owner.product WHERE product_id = p_product_id;
IF v_credit < v_price * p_quantity THEN
RAISE_APPLICATION_ERROR(-20001, 'Insufficient credit for customer '
|| p_customer_id);
END IF;
INSERT INTO ord_owner.orders (customer_id, status, total_amount)
VALUES (p_customer_id, 'pending', v_price * p_quantity)
RETURNING order_id INTO v_order_id;
INSERT INTO ord_owner.order_line (order_id, product_id, quantity, unit_price)
VALUES (v_order_id, p_product_id, p_quantity, v_price);
RETURN v_order_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Customer or product not found');
WHEN OTHERS THEN
-- NEVER `WHEN OTHERS THEN NULL`. It is the worst line in
-- PL/SQL and it is everywhere. Log, keep the backtrace, and
-- RE-RAISE.
INSERT INTO ord_owner.error_log (occurred_at, err_code, err_msg, backtrace)
VALUES (SYSTIMESTAMP, SQLCODE, SQLERRM,
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE; -- <- the line that makes the handler honest
END place_order;
-- ------------------------------------------------------------------
-- BULK COLLECT and FORALL: the context switch, eliminated.
-- ------------------------------------------------------------------
PROCEDURE load_lines(p_order_id NUMBER) IS
TYPE t_lines IS TABLE OF ord_owner.order_line%ROWTYPE;
v_lines t_lines;
BEGIN
SELECT * BULK COLLECT INTO v_lines
FROM ord_owner.order_line_staging
WHERE order_id = p_order_id;
-- One context switch for the whole set, not one per row.
-- On a large set use LIMIT to bound PGA:
-- LOOP FETCH c BULK COLLECT INTO v_lines LIMIT 1000; ... END LOOP;
FORALL i IN 1 .. v_lines.COUNT SAVE EXCEPTIONS
INSERT INTO ord_owner.order_line VALUES v_lines(i);
-- SAVE EXCEPTIONS continues past failures; inspect them after:
-- SQL%BULK_EXCEPTIONS(i).ERROR_INDEX / .ERROR_CODE
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -24381 THEN -- some rows in the FORALL failed
FOR i IN 1 .. SQL%BULK_EXCEPTIONS.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('row ' ||
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX || ': ' ||
SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
END LOOP;
END IF;
RAISE;
END load_lines;
END order_api;
/
-- The difference this makes, measured rather than asserted:
-- row-by-row loop, 100,000 inserts ~45 s
-- FORALL, same 100,000 ~3 s
-- Ratio varies; the order of magnitude does not.
-- ------------------------------------------------------------------
-- Read consistency, from undo. Two sessions.
-- ------------------------------------------------------------------
-- Session A | Session B
-- SELECT SUM(total_amount) |
-- FROM orders; -- long running | UPDATE orders SET total_amount=0;
-- | COMMIT;
-- ... still returns the ORIGINAL sum, reconstructed from undo. The
-- query is consistent with ITS START TIME, not smeared across its run.
--
-- Readers never block writers; writers never block readers. No
-- configuration, no snapshot isolation to enable - it is the only
-- model Oracle has.
-- The failure mode, which is a capacity signal and not corruption:
-- ORA-01555: snapshot too old: rollback segment number N too small
--
-- The query needed an undo version that had been overwritten.
SELECT tablespace_name, retention FROM dba_tablespaces WHERE contents='UNDO';
SHOW PARAMETER undo_retention;
SELECT MAX(maxquerylen) AS longest_query_secs, MAX(tuned_undoretention)
FROM v$undostat; -- size undo for the LONGEST query, not the average
-- ------------------------------------------------------------------
-- Locks and deadlocks.
-- ------------------------------------------------------------------
SELECT s.sid, s.serial#, s.username, s.blocking_session,
s.event, s.seconds_in_wait, q.sql_text
FROM v$session s LEFT JOIN v$sql q ON q.sql_id = s.sql_id
WHERE s.blocking_session IS NOT NULL;
-- ORA-00060: deadlock detected. Oracle rolls back ONE STATEMENT, not
-- the whole transaction, and writes a trace file naming both sessions
-- and the objects:
SELECT value FROM v$diag_info WHERE name = 'Default Trace File';
-- The fix is consistent object access order. A retry is still needed.
Discussion
No questions on this topic yet. Sign in to ask the first one.