This guide is derived from the earlier outline (edition not confirmed) for CACS453 (Database Programming). All units and topics follow the outlined sequence; wording and examples are original student study material, not official TU text.

How to use this guide

Database programming is tested through PL/SQL code writing, trigger design, cursor manipulation, and function/package creation. The exam rewards correct syntax, understanding of when to use each construct, and ability to debug common errors. Practice writing complete PL/SQL blocks, designing triggers for given business rules, and optimizing cursor usage. Marks are awarded for correct compilation, proper exception handling, and clear explanation of design decisions.

Learning Outcomes

By the end of this course, a student should be able to:

  1. Write PL/SQL blocks with proper syntax including declarations, loops, conditional logic, and exception handling.
  2. Design and implement database triggers (BEFORE, AFTER, INSTEAD OF) for given business rules.
  3. Utilize different types of cursors (implicit, explicit, parameterized) for row-by-row processing.
  4. Create stored procedures and functions with input/output parameters for reusable database logic.
  5. Design and implement packages to group related procedures, functions, and variables.

Unit 1: Introduction of RDBMS

Teaching hours: 10

Topics in outline order

  1. Overview of the Oracle Database Architecture
  2. Familiar with SQLPlus, SQLPlus Commands (DESCRIBE, LIST, APPEND, CHANGE, INPUT, DEL, CLEAR BUFFER, Using Script Files), Accepting Values at Runtime, Overview of Fundamental SQL Fundamental Command (DDL, DML, DCL, Join and Subquery)

Explanation

  1. Overview of the Oracle Database Architecture. An Oracle database consists of several key components that work together to store, manage, and retrieve data efficiently. Key components: Tablespaces (logical storage containers, including system tablespace for data dictionary, undo tablespace for transaction rollback, temp tablespace for sorting operations, and user tablespaces for application data), data files (physical files that store the actual data, one or more per tablespace), control files (multiplexed for redundancy, record the physical structure of the database including data file locations, tablespace names, and redo log file locations), redo log files (record all changes made to the database for recovery purposes, multiplexed for protection), parameter file (init.ora/spfile) (database initialization parameters controlling behavior), database instances (combination of Oracle processes and memory structures – PGA, SGA), System Global Area (SGA) (shared memory area containing database buffers, library cache, dictionary cache, redo log buffer, and job queue), and Program Global Area (PGA) (non-shared memory for each session, containing session data, sort area, and PL/SQL values). Process architecture: PMON (process monitor, cleans up failed user processes), SMON (system monitor, performs instance recovery, consolidates free space), DBWN (database writer, writes modified buffers from SGA to data files), LGWR (log writer, writes redo log entries from buffer to redo log files), CKPT (checkpoint, signals DBWN to write), QMN0 (queue monitor, for advanced queueing), and ARCn (archiver, copies redo log to archival location). Understanding the architecture is critical for performance tuning, troubleshooting, and capacity planning.

  2. SQL*Plus Commands. SQL*Plus is Oracle's command-line tool for interacting with the database. Key commands: DESCRIBE (displays the structure of a table, view, or synonym: DESCRIBE tablename), LIST (lists recent SQL commands or SQL buffer contents), APPEND (adds text to the end of the current line in the buffer), CHANGE (replaces a text string in the current line: CHANGE old_text new_text), INPUT (adds new lines after the current line), CLEAR BUFFER (clears the SQL buffer), @ (at sign) (executes a script file), START (equivalent to @, runs a script), PAUSE (displays a message and waits for user input), and SET (changes system variables, e.g., SET SERVEROUTPUT ON enables output display). Script files contain a sequence of SQL and PL/SQL commands saved with .sql extension, executed via @filename or START filename. Accepting values at runtime uses the & symbol (e.g., SELECT * INTO v_var FROM table WHERE column = &parameter) prompting for substitution at execution time.

  3. Fundamental SQL Commands. DDL (Data Definition Language): creates and modifies database structures. CREATE (create table, view, index: CREATE TABLE employees (id NUMBER, name VARCHAR2(100))), ALTER (modify existing structure: ALTER TABLE employees ADD (email VARCHAR2(100))), DROP (delete structure: DROP TABLE employees), TRUNCATE (remove all rows quickly: TRUNCATE TABLE employees), and CREATE INDEX (create index for performance: CREATE INDEX idx_name ON employees(name)). DML (Data Manipulation Language): manipulates data within structures. SELECT (query data), INSERT (add rows: INSERT INTO employees VALUES (1, 'John')), UPDATE (modify rows: UPDATE employees SET name = 'Jane' WHERE id = 1), DELETE (remove rows: DELETE FROM employees WHERE id = 1), and MERGE (upsert operation: merge insert/update). DCL (Data Control Language): control access to data. GRANT (give user permissions: GRANT SELECT, INSERT ON employees TO scott), REVOKE (remove permissions: REVOKE SELECT ON employees FROM scott), and COMMIT / ROLLBACK (transaction control: COMMIT saves changes, ROLLBACK undoes uncommitted changes). Join and Subquery: Joins combine rows from two or more tables: INNER JOIN (matching rows only), LEFT JOIN (all from left, matching from right), RIGHT JOIN (all from right, matching from left), and FULL OUTER JOIN (all rows from both). Subqueries are SELECT statements nested within another SQL statement, used in WHERE, FROM, or HAVING clauses.


Unit 2: PL/SQL

Teaching hours: 13

Topics in outline order

  1. PL/SQL Concepts
  2. Architecture
  3. Block structure
  4. Executing PL/SQL Script
  5. Substitution Variable feature
  6. PL/SQL Language fundamentals
  7. DML Statement in PL/SQL
  8. Transaction Control in PL/SQL. Conditional Control (if, nested if, Case)
  9. Repetitive Control (While, for, simple loop, nested loop, continue, loop label)
  10. DML Statement in PL/SQL
  11. Transaction Control in PL/SQL

Explanation

  1. PL/SQL Concepts. PL/SQL (Procedural Language/SQL) is Oracle's procedural extension to SQL. It combines the data-manipulating power of SQL with the procedural features of a programming language. Key concepts: block structure (the fundamental unit of PL/SQL, consisting of declarative, executable, and exception-handling sections), variables (declared in the declarative section, with types including VARCHAR2, NUMBER, DATE, BOOLEAN, collections, and records), constants (unchanging values defined with the CONSTANT keyword), cursors (work areas for SQL query processing, implicit for single-row queries, explicit for multi-row), procedures (named PL/SQL blocks with parameters, stored in the database), functions (named PL/SQL blocks that return a value, stored in the database), triggers (automatically executing PL/SQL in response to database events), and packages (grouped related procedures, functions, variables, and cursors for modularity and encapsulation). Advantages: improved productivity, better testing (unit testing of procedures/functions), security (encapsulation, hiding implementation details), and reusability (packages across applications).

  2. Architecture. A PL/SQL block is executed by the Oracle engine in three phases: parse (verify syntax, resolve references, compile into an execution plan), execute (run the procedural logic, fetch data via SQL, manipulate data), and close (release resources, close cursors, reset session state). The SQL engine within the Oracle database processes the SQL statements within the PL/SQL block, while the PL/SQL engine manages the procedural control flow. When a PL/SQL block is issued, the API layer calls the PL/SQL compilation unit, which invokes both engines. Error handling: during execution, if a SQL error occurs, an exception is raised; the PL/SQL engine can catch and handle it using the exception-handling section.

  3. Block structure. Every PL/SQL program consists of one or more blocks. Syntax:

DECLARE
  -- declarative section (variables, cursors, exceptions)
BEGIN
  -- executable section (SQL, control structures, loops)
  -- must contain at least one executable statement (NULL is valid)
EXCEPTION
  -- exception-handling section (WHEN ... THEN ...)
END;

Nested blocks: a block can be defined within another block, creating a local scope that shadows or extends the outer block's variables. Naming conventions: variables and parameters should have mnemonic names (e.g., v_employee_id, v_salary). Scope rules: variables are accessible from the point of declaration to the end of the block; inner blocks can reference outer block variables unless shadowed.

  1. Executing PL/SQL Script. PL/SQL blocks can be executed through several interfaces: SQL*Plus (BEGIN ... END; or @script.sql), SQL Developer (visual interface with Debug and Run buttons), Oracle Forms (embedded PL/SQL in triggers and procedures), and JDBC/ODBC (calling via prepareCall or createStatement). Anonymous blocks are blocks without a name, executed inline. Named blocks (procedures, functions, triggers, packages) are stored in the database and can be called by name from other PL/SQL blocks or application code.

  2. Substitution Variable feature. Substitution variables (&variable or &&variable) allow user input at runtime. Single ampersand (&): prompts for value each time the variable is referenced in the block. Double ampersand (&&): prompts once and reuses the value without re-prompting (useful for loop counters or repeated conditions). Examples: SELECT * FROM employees WHERE department_id = &dept_id; (prompt for dept_id value), and &&start_val (prompt once, use for multiple comparisons). Character substitution: CHAR and NCHAR substitution variables can hold strings; use VERIFY OFF to suppress command echoing and FEEDBACK OFF to suppress row count display.

  3. PL/SQL Language fundamentals. Data types: VARCHAR2(size) variable-length character strings, NUMBER(p,s) numeric with precision and scale, DATE date and time (format: 'DD-MON-YY HH24:MI:SS'), BOOLEAN true/false (SQL does not directly manipulate BOOLEAN, use NUMBER(1) as flag), and CHAR(size) fixed-length character strings. Control structures: IF-THEN-ELSE, IF-THEN-ELSIF, nested IF statements, CASE expression (simple case: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE result3 END), and CASE statement (searched case: CASE WHEN condition1 THEN ... WHEN condition2 THEN ... ELSE ... END). Loops: LOOP (basic unconditional loop with EXIT WHEN), WHILE loop (condition at top: WHILE condition LOOP ... END LOOP), FOR loop (iterate over a range: FOR i IN 1..10 LOOP ... END LOOP), and EXIT / EXIT WHEN (terminate loop). Cursor attributes: %ROWCOUNT (number of rows processed), %ISOPEN (whether cursor is open), %FOUND (fetch returned a row), and %NOTFOUND (no row returned).

  4. DML Statement in PL/SQL. DML statements (INSERT, UPDATE, DELETE, MERGE) can be used directly in the executable section of PL/SQL. Key considerations: changes are part of the same transaction as surrounding PL/SQL logic; use COMMIT to save or ROLLBACK to undo; FORALL statement (bulk DML for improved performance: FORALL i IN 1..n INSERT INTO ... VALUES (...)); and BULK COLLECT (retrieve multiple rows into collections: BULK COLLECT INTO collection FROM ...). Example: transferring money between accounts within a PL/SQL block with proper transaction control.

  5. Transaction Control in PL/SQL. Conditional Control (if, nested if, Case). Transaction: a logical unit of work that must be atomic (all-or-nothing). ACID properties: Atomicity (all changes committed or none), Consistency (database transitions from one valid state to another), Isolation (concurrent transactions don't interfere), and Durability (committed changes persist despite failures). COMMIT makes all changes permanent, SAVEPOINT sets a point within a transaction to ROLLBACK to (not back to the beginning), and ROLLBACK undoes all changes since the last COMMIT or SAVEPOINT. Conditional control: IF statement (IF condition THEN ... ELSIF condition2 THEN ... ELSE ... END IF), nested IF (IF condition1 THEN IF condition2 THEN ... END IF;), and CASE (CASE WHEN condition1 THEN result1 ELSE result2 END). Example: validating business rules before committing a transaction.

  6. Repetitive Control (While, for, simple loop, nested loop, continue, loop label). Basic loop: LOOP ... END LOOP with EXIT WHEN condition for termination. WHILE loop: WHILE condition LOOP ... END LOOP (condition evaluated before each iteration). FOR loop: FOR counter IN lower..upper LOOP ... END LOOP (pre-defined range, counter is automatically incremented). CONTINUE: skips the rest of the current iteration and proceeds to the next iteration. Loop label: optional identifier (<<loop_name>>) for loop control in nested loops (EXIT loop_name exits the named loop, CONTINUE loop_name skips to next iteration of named loop). Example: processing a cursor with a loop and using labels to control nested loop behavior.

  7. DML Statement in PL/SQL. (Repeated from topic 7 for emphasis; comprehensive coverage of INSERT, UPDATE, DELETE, MERGE within PL/SQL blocks with error handling and transaction management.)

  8. Transaction Control in PL/SQL. (Repeated from topic 8 for emphasis; comprehensive coverage of transaction management including COMMIT, ROLLBACK, SAVEPOINT, and transaction control within error handling.)


Unit 3: PL/SQL Exception

Teaching hours: 5

Topics in outline order

  1. Exception scope
  2. User-defined exception
  3. Exception propagation
  4. Advance exception concepts (RAISE_APPLICATION_ERROR, EXCEPTION_INIT)

Explanation

  1. Exception scope. An exception is an error or warning condition encountered during PL/SQL execution. Exception scope defines where an exception can be handled: exceptions raised in the executable section propagate upward through nested blocks; if not handled in the current block, they continue to the calling block; if no handler exists in the top-level block, the program terminates with an unhandled exception error. Scope rules: an exception handler can only catch exceptions raised within the same block or its immediate enclosing block; an exception defined in a package specification can be raised and handled from any session using that package; predefined exceptions (e.g., NO_DATA_FOUND, TOO_MANY_ROWS) are globally available; user-defined exceptions must be declared in the declarative section and can be scoped to the block where they are declared unless declared in a package.

  2. User-defined exception. Creating a user-defined exception: declare an exception name in the declarative section (DECLARE invalid_salary EXCEPTION;), raise it explicitly using the RAISE statement (IF salary < 0 THEN RAISE invalid_salary;), and provide an exception handler (EXCEPTION WHEN invalid_salary THEN ...). Pragmas: PRAGMA EXCEPTION_INIT associates a user-defined exception with an Oracle error number, enabling catchment of the exception by error code (DECLARE PRAGMA EXCEPTION_INIT(invalid_salary, -20001);). Best practices: use descriptive names (e.g., out_of_stock_exception), raise errors with meaningful messages (RAISE_APPLICATION_ERROR(-20001, 'Product out of stock')), and handle all foreseeable exceptions.

  3. Exception propagation. When an exception is raised in a block without a handler, it propagates to the enclosing block. This continues until an handler is found or the top-level block is reached, where the exception becomes unhandled and the PL/SQL unit terminates. Example: a procedure calls a sub-procedure which raises an exception; if the sub-procedure's exception handler does not re-raise, the exception does not propagate to the caller; if it re-raises (RAISE;), the exception propagates. The RAISE_APPLICATION_ERROR procedure creates a custom error number (-20001 to -20999) and message, which can be caught by application code. Exception chaining: one exception can cause another (e.g., a constraint violation triggers a predefined exception which triggers a user-defined handler).

  4. Advance exception concepts (RAISE_APPLICATION_ERROR, EXCEPTION_INIT). RAISE_APPLICATION_ERROR syntax: RAISE_APPLICATION_ERROR(error_number, message, keep_errors) where error_number is between -20001 and -20999 (negative Oracle error codes), message is the error text (up to 2000 bytes), and keep_errors (TRUE retains previous error messages, FALSE replaces them). PRAGMA EXCEPTION_INIT associates an exception name with an Oracle error: PRAGMA EXCEPTION_INIT(my_except, -1403) where -1403 is "NO_DATA_FOUND". This enables WHEN my_except THEN ... to catch error -1403. Custom error numbers: avoid using Oracle-reserved error numbers (-20001 to -20999 are user-defined range). Example: creating a trigger that validates employee salary and raises a custom error if below minimum wage.


Unit 4: Database Cursors

Teaching hours: 5

Topics in outline order

  1. Types of cursors
  2. Cursor loop
  3. Nested cursors cursor for loops
  4. Parameterized cursors
  5. Nested cursors

Explanation

  1. Types of cursors. A cursor is a work area storing information about a SQL query execution. Implicit cursor: automatically created by Oracle for single-row DML statements (INSERT, UPDATE, DELETE returning with clause) and SELECT INTO queries returning exactly one row. Attributes: %ROWCOUNT (number of rows affected), %ISOPEN (always TRUE for implicit cursor after execution), %FOUND (TRUE if the DML affected at least one row), and %NOTFOUND (TRUE if no rows affected). Explicit cursor: declared and managed by the programmer for multi-row queries. Lifecycle: DECLARE cursor_name CURSOR FOR SELECT ...; (definition), OP cursor_name; (opens the query, loads result set), FETCH cursor_name INTO variable_list; (retrieves one row into variables), CLOSE cursor_name; (releases the work area). Cursor attributes: %ROWCOUNT (cumulative count of fetched rows), %NOTFOUND (TRUE if last fetch returned no row), %FOUND (TRUE if last fetch returned a row), and %ISOPEN (TRUE if cursor is open). Parameterized cursor: explicit cursor with parameters (CREATE OR REPLACE PROCEDURE ... IS cursor_name CURSOR FOR SELECT ... FROM table WHERE column = parameter;). Cursor FOR loop: implicit cursor management (FOR record_name IN cursor_name LOOP ... END LOOP;) automatically opens, fetches, and closes the cursor.

  2. Cursor loop. Basic pattern:

DECLARE
  CURSOR c_name IS SELECT column_list FROM table_name WHERE condition;
  v_var1 table.column_type%TYPE;
  v_var2 table.column_type%TYPE;
BEGIN
  OPEN c_name;
  LOOP
    FETCH c_name INTO v_var1, v_var2;
    EXIT WHEN c_name%NOTFOUND;
    -- process v_var1, v_var2
  END LOOP;
  CLOSE c_name;
END;

Alternative: use FOR c_record IN c_name LOOP ... END LOOP; which handles open/fetch/exit/close automatically. Cursor with parameters: WHERE column = parameter_value passed during the FOR loop or OPEN statement.

  1. Nested cursors cursor for loops. Nested cursor: a cursor defined within another cursor's loop, used for querying related data for each row. Pattern:
FOR outer_rec IN outer_cursor LOOP
  -- process outer row
  FOR inner_rec IN INNER_CURSOR(outer_rec.id) LOOP
    -- process inner row related to outer row
  END LOOP;
END LOOP;

Example: for each employee, retrieve their department name and total salary of their department. Caution: nested loops can be expensive (N × M queries); consider joins or aggregation for performance. Cursor parameters: the inner cursor can reference the outer cursor's columns (e.g., WHERE department_id = outer_rec.department_id).

  1. Parameterized cursors. Explicit cursor with parameters enables reusable query logic. Syntax:
CREATE OR REPLACE PROCEDURE get_emp_dept(p_deptno NUMBER) IS
  CURSOR c_emp IS SELECT empno, ename, sal FROM emp WHERE deptno = p_deptno;
  v_emp c_emp%ROWTYPE;
BEGIN
  OPEN c_emp USING p_deptno;
  LOOP
    FETCH c_emp INTO v_emp;
    EXIT WHEN c_emp%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_emp.ename || ' - ' || v_emp.sal);
  END LOOP;
  CLOSE c_emp;
END;

Advantages: improved security (parameter values are bind variables, preventing SQL injection), reusability (same cursor with different parameters), and performance (bind variable peeking optimization). Example: a report generating department-wise employee lists.

  1. Nested cursors. (Same as nested cursor for loops above; emphasis on using cursors within cursor FOR loops and the importance of proper cursor management for resource cleanup.)

Unit 5: Database Triggers

Teaching hours: 5

Topics in outline order

  1. Database Triggers BEFORE
  2. AFTER Triggers
  3. Row and statement triggers
  4. INSTEAD OF triggers

Explanation

  1. Database Triggers BEFORE. A BEFORE trigger executes before the triggering event (INSERT, UPDATE, DELETE). Use cases: validate data before it's written (e.g., check that salary is positive), set default values (:NEW.column := default_value), and modify the new values (:NEW.salary := :OLD.salary * 1.1 for a 10% raise). Syntax: CREATE OR REPLACE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN ... END; Key components: trigger_name (identifier), BEFORE (timing), INSERT/UPDATE/DELETE (event), ON table_name (target table), FOR EACH ROW (row-level vs. statement-level), and :NEW (new row values, modifiable in BEFORE triggers). Example: a BEFORE INSERT trigger on an employees table ensures hire_date is not set in the future: IF :NEW.hire_date > SYSDATE THEN RAISE_APPLICATION_ERROR(-20001, 'Hire date cannot be in the future'); END IF;

  2. AFTER Triggers. An AFTER trigger executes after the triggering event completes. Use cases: maintain audit logs (record changes in a separate audit table), propagate changes to other tables, and perform calculations based on the changed data. Syntax: CREATE OR REPLACE TRIGGER trigger_name AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END; Key difference: :NEW values are available and modifiable (though the event has already occurred, so modifying :NEW has limited effect); :OLD values are available for reading (the original data before the change). Example: an AFTER INSERT trigger on the employees table adds a record to an audit table: INSERT INTO emp_audit VALUES (:NEW.empno, :NEW.ename, SYSDATE, 'INSERT');

  3. Row and statement triggers. Row-level trigger (FOR EACH ROW): executes once for each row affected by the triggering event. Use cases: row-specific validation, modifying per-row values, and complex per-row logic. **Statement-level trigger (default if FOR EACH ROW omitted):** executes once per SQL statement, regardless of how many rows are affected. **Use cases:** summary operations, checking conditions across all affected rows, and actions that should happen once per statement. **Comparison:** row-level executes N times (N = affected rows), statement-level executes 1 time. **Example:** a statement-level trigger after batch UPDATE logs the total number of rows updated: DECLARE v_count INTEGER := SQL%ROWCOUNT; INSERT INTO audit (action, count, timestamp) VALUES ('UPDATE', v_count, SYSDATE);`

  4. INSTEAD OF triggers. An INSTEAD OF trigger executes instead of the triggering event, primarily on views that are otherwise not updatable. Use cases: make complex views (with JOINs, GROUP BY, DISTINCT) updatable, handle inserts/updates/deletes on views with multiple underlying tables, and enforce complex business rules on view data. Syntax: CREATE OR REPLACE TRIGGER trigger_name INSTEAD OF INSERT ON view_name FOR EACH ROW BEGIN ... END; How it works: instead of performing the actual INSERT/UPDATE/DELETE on the view, the trigger body implements the corresponding operations on the underlying base tables. Example: a view v_employee_dept joining employees and departments; an INSTEAD OF INSERT trigger inserts into both the employees and departments tables appropriately, allowing INSERT INTO v_employee_dept VALUES (...) to work.


Unit 6: Record and Procedures

Teaching hours: 5

Topics in outline order

  1. Record (Record types, Nested record)
  2. Procedure (Block Structure, Anonymous Block, creating procedure, IN, OUT parameters in Procedure)

Explanation

  1. Record. A record is a PL/SQL data structure that groups related fields of different types, similar to a row in a table but not requiring a database table. Record types: simple record (declared as record_name record_type%ROWTYPE; where record_type is a table name, capturing all columns of a row), nested record (a record within a record, useful for hierarchical data), and collection of records. Declaration: DECLARE v_emp_rec employees%ROWTYPE; (declares a record with all columns of the employees table). Attributes: v_emp_rec.ename accesses the ename field, and %TYPE attribute ensures type compatibility when table structure changes. Nested record example: DECLARE v_parent rec_type := rec_type(10, 'John'); v_child rec_child_type := rec_child_type(20, v_parent);

  2. Procedure. A procedure is a named PL/SQL block that performs a specific task, can accept parameters, and does not return a value (use NULL or DBMS_OUTPUT for output). Procedure creation: CREATE OR REPLACE PROCEDURE procedure_name (parameter_list) IS/variables BEGIN statements EXCEPTION exception_handling END; Parameter modes: IN (pass value to procedure, default, cannot be modified by procedure), OUT (return value from procedure, initialized to NULL, set by procedure), and IN OUT (pass initial value and return modified value). Example: a procedure calculating employee salary raise: CREATE OR REPLACE PROCEDURE give_raise (p_empno NUMBER, p_percentage IN NUMBER) IS v_sal NUMBER; BEGIN SELECT sal INTO v_sal FROM emp WHERE empno = p_empno; UPDATE emp SET sal = v_sal * (1 + p_percentage/100) WHERE empno = p_empno; END; Anonymous procedure: BEGIN give_raise(123, 10); END; (executes the procedure with emp number 123 and 10% raise).


Unit 7: Functions and Package

Teaching hours: 5

Topics in outline order

  1. Functions (creating and invoking function and optimizing function in execution)
  2. Creating packages
  3. Extending the package
  4. Package instantiation and initialization

Explanation

  1. Functions. A function is a named PL/SQL block that returns a single value, used in SQL expressions. Creation: CREATE OR REPLACE FUNCTION function_name (parameter_list) RETURN return_type IS v_variables BEGIN RETURN value; EXCEPTION ... END; Key difference from procedure: functions can be called from SQL statements (e.g., SELECT function_name(col) FROM table), must return the specified type, and should be deterministic (same input always same output) for optimal query performance. Example: a function calculating years of service: CREATE OR REPLACE FUNCTION years_of_service (p_hire_date DATE) RETURN NUMBER IS v_years NUMBER; BEGIN SELECT MONTHS_BETWEEN(SYSDATE, p_hire_date) / 12 INTO v_years FROM DUAL; RETURN ROUND(v_years); END; Function from SQL: SELECT empno, ename, years_of_service(hire_date) FROM emp;

  2. Creating packages. A package groups related procedures, functions, variables, and cursors into a single unit. Package specification (visible to users): declares public types, variables, constants, cursors, procedures, and functions. Package body (hidden implementation): contains the actual code for procedures and functions, plus private types, variables, and cursors not visible to users. Advantages: encapsulation (hide implementation details), modularity (group related logic), state retention (package-level variables persist across calls), and overloading (multiple procedures/functions with same name but different parameters). Package skeleton:

CREATE PACKAGE emp_pkg IS
  PROCEDURE give_raise (p_empno NUMBER, p_percentage NUMBER);
  FUNCTION years_of_service (p_hire_date DATE) RETURN NUMBER;
  v_max_sal CONSTANT NUMBER := 9999;
END emp_pkg;
/
CREATE PACKAGE BODY emp_pkg IS
  PROCEDURE give_raise (p_empno NUMBER, p_percentage NUMBER) IS
    v_sal NUMBER;
  BEGIN
    SELECT sal INTO v_sal FROM emp WHERE empno = p_empno;
    UPDATE emp SET sal = v_sal * (1 + p_percentage/100) WHERE empno = p_empno;
  END;
  FUNCTION years_of_service (p_hire_date DATE) RETURN NUMBER IS
    v_years NUMBER;
  BEGIN
    SELECT MONTHS_BETWEEN(SYSDATE, p_hire_date) / 12 INTO v_years FROM DUAL;
    RETURN ROUND(v_years);
  END;
END emp_pkg;
/
  1. Extending the package. Adding new procedures/functions to an existing package: CREATE OR REPLACE PACKAGE emp_pkg IS ... ADD NEW DECLARATIONS ... END; and CREATE OR REPLACE PACKAGE BODY emp_pkg IS ... ADD NEW IMPLEMENTATIONS ... END;. Overloading: define multiple procedures/functions with the same name but different parameter signatures (different number, type, or mode of parameters). Example: PROCEDURE give_raise (p_empno NUMBER) and PROCEDURE give_raise (p_empname VARCHAR2) - same name, different parameters. Package variables: persist across procedure calls within the same session, enabling stateful operations (e.g., counter, accumulator).

  2. Package instantiation and initialization. Package initialization: code in the package body runs once per session when the package is first referenced (loaded into memory). This is ideal for initialization code (setting package-level variable values, opening cursors, logging startup events). Package state: package-level variables retain their values across procedure/function calls within the same session, enabling stateful designs (e.g., session-specific counters, caching). Calling package objects: emp_pkg.give_raise(123, 10); (procedure) and SELECT emp_pkg.years_of_service(hire_date) FROM emp; (function). Dependency invalidation: if the package specification is altered, dependent objects may be invalidated and recompiled; package body alterations do not invalidate dependent objects if the specification remains unchanged.


Key Terms (Comprehensive)

database programming · RDBMS · Oracle Database · SQL*Plus · architecture · tablepaces · data files · control files · redo log files · parameter file · instance · PMON · SMON · DBWN · LGWR · CKPT · QMN0 · ARCn · PGA · SGA · PL/SQL · block structure · declarative section · executable section · exception-handling section · variables · constants · cursors · implicit cursor · explicit cursor · attributes · %ROWCOUNT · %ISOPEN · %FOUND · %NOTFOUND · DML · DDL · DCL · COMMIT · ROLLBACK · SAVEPOINT · transaction · ACID · exception · user-defined exception · RAISE · PRAGMA EXCEPTION_INIT · scope · block · nested block · NULL · substitution variable · DML · transaction control · conditional control · IF · CASE · loop · LOOP · WHILE LOOP · FOR LOOP · CONTINUE · loop label · label · DML statements · INSERT · UPDATE · DELETE · MERGE · FORALL · BULK COLLECT · exception handling · RAISE_APPLICATION_ERROR · TRIGGER · BEFORE · AFTER · FOR EACH ROW · statement-level · INSTEAD OF · view · ROW · Record · %ROWTYPE · procedure · function · parameter modes · IN · OUT · IN OUT · package · package specification · package body · overloading · package initialization · package state · deterministic


References from the Source Syllabus

  • CACS453 Database Programming course outline (2018), TU FOHSS PDF pp. 138-140
  • Oracle PL/SQL Language Reference, Oracle Documentation
  • Steven Feuerstein, "Oracle PL/SQL Programming", O'Reilly, 2014
  • Mark Stringer, "PL/SQL Best Practices", O'Reilly, 2005
  • Robert Freeman, "SQL and PL/SQL for Oracle 11g", Cengage Learning, 2011

End of Guide