Explain PL/SQL: procedures, functions, packages, and bulk processing.
PL/SQL is Oracle's procedural extension to SQL, running inside the database.
Building blocks
- Anonymous blocks:
DECLARE ... BEGIN ... EXCEPTION ... END; - Procedures perform actions; functions return a value and can be used in SQL.
- Packages group related types, variables, procedures and functions with a specification (public API) and a body (implementation). Benefits: encapsulation, package state per session, one compiled unit loaded at once, and dependencies that do not break when only the body changes.
- Triggers run on DML or DDL events (use sparingly; they hide logic).
- Exceptions: predefined (
NO_DATA_FOUND,TOO_MANY_ROWS,DUP_VAL_ON_INDEX) and user-defined withRAISE_APPLICATION_ERROR(-20001, 'message').
Performance: avoid row-by-row
Each switch between the PL/SQL and SQL engines (a context switch) costs time. Process collections in bulk:
BULK COLLECT INTOfetches many rows at once (useLIMITto cap memory).FORALLsends a whole collection of DML to SQL in one call;SAVE EXCEPTIONSkeeps going on row errors. Better still, do it in a single SQL statement (INSERT ... SELECT,MERGE) when possible.
Example
sql
CREATE OR REPLACE PACKAGE order_api AS
PROCEDURE close_stale_orders(p_days IN PLS_INTEGER, p_closed OUT PLS_INTEGER);
END order_api;
/
CREATE OR REPLACE PACKAGE BODY order_api AS
PROCEDURE close_stale_orders(p_days IN PLS_INTEGER, p_closed OUT PLS_INTEGER) IS
TYPE t_ids IS TABLE OF orders.order_id%TYPE;
l_ids t_ids;
CURSOR c IS SELECT order_id FROM orders
WHERE status = 'NEW' AND created_at < SYSDATE - p_days;
BEGIN
p_closed := 0;
OPEN c;
LOOP
FETCH c BULK COLLECT INTO l_ids LIMIT 1000; -- 1,000 rows per round trip
EXIT WHEN l_ids.COUNT = 0;
FORALL i IN 1 .. l_ids.COUNT -- one call to the SQL engine
UPDATE orders SET status = 'CLOSED' WHERE order_id = l_ids(i);
p_closed := p_closed + SQL%ROWCOUNT;
END LOOP;
CLOSE c;
EXCEPTION
WHEN OTHERS THEN
IF c%ISOPEN THEN CLOSE c; END IF;
RAISE;
END close_stale_orders;
END order_api;
/The simplest version is one statement: UPDATE orders SET status = 'CLOSED' WHERE status = 'NEW' AND created_at < SYSDATE - :days.
Follow-up questions interviewers ask
Try answering each one before you open it.
How do you call a PL/SQL procedure from Spring?
With SimpleJdbcCall (new SimpleJdbcCall(jdbcTemplate).withCatalogName("ORDER_API").withProcedureName("CLOSE_STALE_ORDERS").execute(Map.of("P_DAYS", 30))), a JPA @NamedStoredProcedureQuery / @Procedure in Spring Data, or a CallableStatement ({call order_api.close_stale_orders(?, ?)}).