Search This Blog

Tuesday, June 24, 2025

Understanding PL/SQL in Oracle APEX

PL/SQL (Procedural Language/Structured Query Language) is Oracle’s procedural extension of SQL, and it plays a critical role in Oracle APEX development. In Oracle APEX, PL/SQL is used to define business logic, control data processing, interact with the database, and automate workflows within applications. Understanding PL/SQL is essential for building powerful, data-driven applications that go beyond basic form and report functionality.

PL/SQL is essential in APEX because it allows you to:

  • Implement business logic within an application

  • Create dynamic actions and processes

  • Perform validations and error handling

  • Write stored procedures and functions

  • Manage triggers and packages for better modularity

Where PL/SQL is Used in Oracle APEX

  • Page Processes: PL/SQL is commonly used in page processes to perform actions such as inserting, updating, or deleting data after a form is submitted.

  • Validations: You can write PL/SQL logic to validate user input before saving it to the database.

  • Dynamic Actions: When a page element triggers a dynamic action, PL/SQL can be used on the server side to execute logic and return results to the client.

  • Application Processes: For actions that apply across multiple pages or during session initialization, PL/SQL is written in application-level processes.

  • PL/SQL Regions: These allow developers to embed PL/SQL directly in a page to generate custom HTML output or perform logic-driven display.

PL/SQL Code Structure
PL/SQL code is typically written in the form of anonymous blocks or stored procedures and follows this structure:

DECLARE
  -- variable declarations
BEGIN
  -- executable statements
EXCEPTION
  -- error handling
END;

What Are the Differences Between SQL and PL/SQL Code Structure


SQL and PL/SQL are both used in Oracle APEX and Oracle Database, but they have different code structures and purposes. Understanding the difference helps you use each correctly in your applications.

1. SQL Code Structure
  • SQL is a declarative language.

  • It works with one statement at a time.

  • Each SQL command performs a specific task like retrieving or modifying data.

  • SQL does not support control structures like IF or LOOP.

Example of SQL code structure:

SELECT first_name, last_name FROM employees WHERE department_id = 10;

Other SQL examples:

INSERT INTO departments (department_name) VALUES ('Marketing');
UPDATE employees SET salary = 5000 WHERE employee_id = 101;
DELETE FROM employees WHERE employee_id = 102;

2. PL/SQL Code Structure

  • PL/SQL is a procedural language that includes SQL and additional programming features.

  • It allows multiple statements in a block.

  • It supports variables, loops, conditions, and error handling.

  • PL/SQL is used to build stored procedures, functions, and anonymous blocks.


Basic PL/SQL block structure:

DECLARE
  v_name VARCHAR2(50);
BEGIN
  SELECT first_name INTO v_name FROM employees WHERE employee_id = 101;
  DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_name);
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('No employee found.');
END;

Key differences in structure:

  • SQL has no DECLARE, BEGIN, or EXCEPTION sections.

  • PL/SQL uses a block structure: DECLARE (optional), BEGIN, EXCEPTION (optional), and END.

  • SQL is for querying or updating data. PL/SQL is for building logic and control.

Summary

  • Use SQL when you need a single query or data manipulation command.

  • Use PL/SQL when you need to write logic that includes multiple steps, variables, or error handling.
    Both are essential in Oracle APEX development and often work together to build dynamic, data-driven applications.

Common Use Cases in APEX
  • Automatically updating audit fields (created date, modified by)

  • Performing complex validations based on multiple inputs

  • Sending emails or notifications using APEX_MAIL

  • Inserting or updating multiple related tables in one process

  • Calling stored procedures and packages for backend operations

Benefits of Using PL/SQL in APEX

  • Performance: Code runs inside the database, reducing network overhead.

  • Reusability: Logic written once in procedures or functions can be reused across different pages or applications.

  • Security: Business rules are enforced at the database level, reducing reliance on UI-based validation.

  • Maintainability: Keeps complex logic out of the page and centralized in packages or procedures.


SQL (Structured Query Language) and PL/SQL (Procedural Language/SQL) are both used in Oracle databases, but they serve different purposes and have different capabilities. Here's a clear breakdown:


1. Purpose

  • SQL is a declarative language used to interact with the database — for querying, inserting, updating, and deleting data.

  • PL/SQL is a procedural language that extends SQL with programming features like loops, conditions, variables, and error handling.


2. Execution

  • SQL executes one statement at a time (single-line operations).

  • PL/SQL can execute multiple statements as a block, including logic and control flow.


3. Language Type

  • SQL is a data manipulation language (DML).

  • PL/SQL is a procedural language that embeds SQL statements inside structured code.


4. Capabilities

  • SQL can:

    • Select data (SELECT)

    • Insert, update, delete records

    • Create and modify database objects

  • PL/SQL can:

    • Declare variables and constants

    • Use loops (FOR, WHILE) and conditions (IF, CASE)

    • Handle exceptions (EXCEPTION block)

    • Define procedures, functions, packages, and triggers


5. Reusability

  • SQL is typically written and run per use case.

  • PL/SQL allows you to create reusable blocks like stored procedures and functions.


6. Performance

  • PL/SQL improves performance by reducing round-trips between application and database, especially in complex logic.

  • SQL may require multiple calls to achieve the same, especially in procedural logic.


7. Example

SQL Example:

SELECT first_name FROM employees WHERE department_id = 10;

PL/SQL Example:

DECLARE
  v_name employees.first_name%TYPE;
BEGIN
  SELECT first_name INTO v_name FROM employees WHERE employee_id = 101;
  DBMS_OUTPUT.PUT_LINE('Name: ' || v_name);
END;

Summary

  • Use SQL when you need to interact with data directly (query or modify).

  • Use PL/SQL when you need to perform logic, automation, or control flow inside the database.
    Both are often used together in Oracle APEX and database development to build powerful, efficient applications

When to Use PL/SQL vs. SQL

SQL is used when you need to perform simple operations directly on the data, such as selecting, inserting, updating, or deleting rows in a table. It is best for straightforward queries and data manipulation tasks. Use SQL when you want to retrieve data from a table, filter it with conditions, or make basic changes to one or more records.

PL/SQL should be used when you need to include logic, decision-making, or processing that involves more than one SQL statement. It is ideal when your task requires conditions, loops, error handling, or variables. PL/SQL is useful for writing stored procedures, functions, packages, and triggers where the operations are more complex or need to be reused across different parts of the application.

Use SQL for single operations on data. Use PL/SQL when you need to wrap SQL in a logical structure that includes control flow, calculations, or exception handling. In Oracle APEX, PL/SQL is often used in page processes, validations, and backend logic, while SQL is used for queries, report sources, and data display.

Where Do We Use PL/SQL and SQL in Oracle APEX

In Oracle APEX, both PL/SQL and SQL are used throughout the application to manage data and implement business logic. SQL is used for querying and manipulating data, while PL/SQL is used when procedural logic, conditions, or loops are needed. They often work together to power the dynamic behavior of APEX applications.

Where SQL is Used

  • In report regions to fetch data using SELECT statements

  • In form regions to read and write table data

  • In LOVs (List of Values) to populate dropdowns with query results

  • In validations and computations to retrieve or calculate values

  • In dynamic actions that execute SQL statements to get results quickly

Where PL/SQL is Used

  • In page processes to insert, update, delete, or validate data with logic

  • In page-level or application-level validations using conditional rules

  • In page-level or region-level dynamic PL/SQL code blocks

  • In PL/SQL anonymous blocks for executing stored procedures or functions

  • In before and after submit processes to control page flow or behavior

  • In custom authentication, authorization, and session management logic

SQL is best used when you are interacting with the data directly. PL/SQL is used when you need to wrap those interactions with logic, conditions, or exception handling. Oracle APEX makes it easy to combine both, so you can create responsive, intelligent, and secure applications.

Where Inside Oracle APEX Do We Add PL/SQL and SQL Code

Oracle APEX provides several areas where you can directly add PL/SQL and SQL code to control how your application behaves and interacts with the database. These areas are built into the APEX Page Designer and SQL Workshop, making it easy to use SQL for data access and PL/SQL for procedural logic.

1. SQL Workshop

  • Use SQL Commands to write and run ad hoc SQL and PL/SQL.

  • Use SQL Scripts to save and execute longer SQL or PL/SQL blocks.

  • Use Object Browser to create tables, views, procedures, and functions using SQL and PL/SQL.

2. Report and Form Regions

  • In Classic or Interactive Reports, you use SQL queries to define the data source.

  • In Forms, SQL is used to fetch and save data directly from tables or views.

  • You can also use PL/SQL for logic-based column values using expressions or functions.

3. Page Processes

  • PL/SQL is added here to run after page submission or on page load.

  • Used for inserting, updating, or deleting records with custom logic.

  • Useful for calling stored procedures or performing validations.

4. Dynamic Actions

  • PL/SQL can be added as server-side code when a dynamic action is triggered.

  • SQL can be used as part of true/false condition checks or value assignments.

5. Computations

  • Add SQL or PL/SQL code to calculate or set page item values before or after page rendering.

6. Validations

  • PL/SQL expressions or functions are used to create custom validation rules for form items.

  • SQL queries can be used to check if a value exists or meets specific conditions.

7. LOVs (List of Values)

  • SQL queries are used to populate dropdowns, radio groups, and checkbox groups with dynamic values from the database.

8. Page Items and Regions

  • You can set default values using SQL queries.

  • PL/SQL expressions can be used in conditions to show or hide items or regions.

9. Application Processes and Shared Components

  • PL/SQL can be defined as a global process or function to be reused across pages.

  • Useful for authentication, authorization, and session-level operations.

10. PL/SQL Dynamic Content Regions

  • Allows you to write full PL/SQL blocks that generate HTML output directly within a region.

Oracle APEX is tightly integrated with SQL and PL/SQL, allowing you to apply database logic exactly where it’s needed — whether it’s displaying data, validating inputs, or controlling behavior at the page or application level.

Conclusion
PL/SQL is the backbone of dynamic and powerful Oracle APEX applications. It allows developers to implement complex logic, enforce business rules, and interact efficiently with the database. By mastering PL/SQL, you gain full control over your application's behavior, making it more robust, secure, and scalable. Whether you're processing data, validating input, or building custom logic, PL/SQL is an essential tool in your APEX toolkit.

How Do I Use Workflows

 How to Make and Use Workflows in Oracle APEX

Workflows in Oracle APEX help automate processes by defining a series of steps, conditions, and approvals. A workflow ensures that business processes follow a structured and repeatable path. This tutorial explains how to create, configure, and use workflows in APEX using APEX Automations and Oracle Workflow Engine.

Workflows is all about automating business processes that move documents, tasks, and information from one participating user to another while following a set off rules defined by the developer.

Important--- A workflow does not return a value via a parameter.


Understanding Workflows in APEX

A workflow consists of:

  • Steps: Actions that need to be performed.

  • Conditions: Rules that determine how the process flows.

  • Approvals: Checks and verifications before moving to the next step.

  • Notifications: Alerts sent when actions are required.

Workflows can be used for:

  • Approval processes (e.g., expense approvals, leave requests).

  • Data validation and transformation (e.g., checking order details before processing).

  • Automated notifications (e.g., sending emails based on user actions).


Creating a Workflow in APEX

Step 1: Enable APEX Automations

  1. Log in to Oracle APEX.

  2. Open your application.

  3. Go to SQL Workshop > RESTful Services and ensure that REST-enabled SQL is available (needed for some automations).

  4. Navigate to Shared Components > Automations.

  5. Click Create to start a new automation process.


Step 2: Define Workflow Steps

  1. Enter a name for the automation (e.g., “Expense Approval Workflow”).

  2. Select a triggering event

    • A table change (INSERT, UPDATE, DELETE).

    • A scheduled time (e.g., run every hour).

  3. Choose the data source

    • A database table.

    • A SQL Query.

Example Query:

SELECT request_id, amount, status FROM expense_requests WHERE status = 'Pending';

This fetches pending approval requests.


Step 3: Add Actions to the Workflow

  1. Click Add Action to define workflow steps.

  2. Choose an action type

    • PL/SQL Code: Run a function or procedure.

    • Send Email: Notify a manager for approval.

    • Call Web Service: Integrate with external systems.

    • Update Table Row: Change status after approval.

Example PL/SQL Action to mark an expense as approved:

UPDATE expense_requests  

SET status = 'Approved'  

WHERE request_id = :REQUEST_ID;


Step 4: Add Approval Conditions

  1. Click Add Condition.

  2. Set conditions based on column values.

Example:

  • If amount > 1000, require manager approval.

  • If amount ≤ 1000, approve automatically.

Condition Query:

SELECT CASE  

  WHEN amount > 1000 THEN 'Manager Approval Required'  

  ELSE 'Auto Approved'  

END AS approval_status  

FROM expense_requests;


Using the Workflow in APEX Pages

Once the automation is set up, it can be integrated into APEX pages:

  1. Approval Dashboard

    • Create an Interactive Report with SELECT * FROM expense_requests;.

    • Add a button for managers to approve or reject requests.

  2. Automated Email Notifications

    • Use Send Email Action in APEX Automations to notify managers.

BEGIN  

   APEX_MAIL.SEND (  

      p_to => 'manager@example.com',  

      p_from => 'system@example.com',  

      p_subj => 'Expense Approval Required',  

      p_body => 'A new expense request requires your approval.'  

   );  

END;

  1. User Notifications 

    • Use APEX Messages to show alerts when an expense is processed.

    • Add a Success Message in APEX Processing Steps.


Benefits of Using Workflows in APEX

Feature

Benefit

Automates tasks

Reduces manual effort for approvals, notifications, and updates.

Improves efficiency

Ensures that business processes follow a structured path.

Enhances tracking

Keeps records of approvals, rejections, and escalations.

Integrates with external systems

Calls APIs or updates remote databases automatically.

Workflows in APEX streamline business processes, reduce errors, and improve automation. They can be used in approval systems, ticketing solutions, inventory management, and many other applications.




EXAMPLE:

Creating the Workflow is created by navigating to Shared Components  > Workflows and Automations

A black screen with yellow and orange text

Description automatically generated

That carries us to Workflow definition, this is the area that will be used to create the complete workflow. A workflow is made from various workflow actions

Workflow – This is the top level of the workflow.

Version – Sets the specific state of workflow. A workflow can be placed in one of three version.

Development

Workflows are editable, but you can only run them in the developer session. Only one version of a workflow can be in development at a time.

Active

Workflows are partially editable. Only one version of a workflow can be active at a time. You cannot move an active workflow back to in development.

Inactive

Workflows are no longer active, and you cannot use an inactive version of a workflow to start a new workflow instance. Multiple versions of a workflow can be inactive at a time. You can delete an inactive workflow. Deleting an inactive workflow definition also deletes any workflow instances associated with it.


You can only run one workflow a version at a time. When you’re working on your workflow it is set to Development, once you’re done working on the workflow you then set it to Active. Only one workflow can be active at a time. Any workflow that is not set to Active will be set to Inactive.

Each Workflow Version is made from the following:

  • Parameters – Workflow input variables that are used to pass values into the workflow. These are the values that will be used to define the activities within the workflow.

  • Variables – Variables used inside of the workflow.

  • Activities -Specific action available to be used within the workflow.

  • Connections – These link activities together.

  • Participants – The users that have privileges to operate within the workflow.


Activities – There are 9 types of activities available to workflows

  • Workflow Start

  • Human Tasks

  • Invoke API

  • Execute Code

  • Send Email

  • Send Push Notification

  • Switch

  • Wait

  • Workflow End

A screenshot of a computer

Description automatically generated

A workflow might look like the following in the workflow designer

A screenshot of a computer

AI-generated content may be incorrect.

 An example of a workflow

Requirements

  1. We want to pass a number to the workflow. If the number is greater than 100 then we are going to save the value into a table with a message that states which branch was chosen(True or False).

  2. We want to display the workflow id back into the application page.



Step 1 – Create the initiating page with two fields and one button

  • Item - Amount

  • Item - WFID

  • Button - StartWorkflow



It should look something like this:

A screenshot of a computer

Description automatically generated


Step 2 – Create the workflow

A screen shot of a computer

AI-generated content may be incorrect.


Step 3 -  Set the parameter

A screenshot of a computer

AI-generated content may be incorrect.

A screenshot of a computer

AI-generated content may be incorrect.

Step 4 – Set the “Start” Activity and change the values as follows.

A screenshot of a computer

AI-generated content may be incorrect.

Step 5 – Add the True/false switch and set the values

A screenshot of a computer

AI-generated content may be incorrect.

Set Name: True False Switch

Set Type: switch

Set Switch: Type > True False Check

Set Condition > Condition Type: Expression

Set Condition >Expression: “:JS_PARAMETER >  100”


Step 6 – Create “True” Activity

A screenshot of a computer

AI-generated content may be incorrect.

Set Identification > Name > Activity_True

Set Identification > Type > Execute Code

Set Source > Local > Location Database

Set Source > Language > PL/SQL

Set Source > Local > PL/SQL Code

Here is the code: 

insert into  wftable (amount, wfid, path)

values

(:JS_PARAMETER ,'def', 'True: Greater than 100');


Step 7 – Create “False” Activity – duplicate the “True” activity with the following changes

A screenshot of a computer

Description automatically generated

Set Identification > Name > Activity_false

Set Source > Local > PL/SQL Code

Here is the code: 

insert into  wftable (amount, wfid, path)

values

(:JS_PARAMETER ,'abc', 'False: Less than than 100');


Step 8 – Create the “End” activity.

A screenshot of a computer

AI-generated content may be incorrect.

Identification > Name: End

Identification> Type > Workflow End

Settings > End State > Completed


Step 9 -Create a process in the request page

A screenshot of a computer

Description automatically generated

Add the following changes

A black and grey striped object

Description automatically generated

Set the type to “Start”

Definition: Set the name of the definition to the name of the Workflow

Workflow Id Item: This sets the Workflow’s id into the P2_WFID textbox in the page.

A black and grey striped background

Description automatically generated

This setting is the Success message that gets displayed after the object is processed

A black rectangular object with a black stripe

Description automatically generated 

Looks like this:

A screenshot of a computer

Description automatically generated


A green and blue sign with white text

AI-generated content may be incorrect.

Set the server-side condition:

---StartWorkflow is the name of the button that will fire off the process.

A black rectangular object with black lines

Description automatically generated


Step 10 – Set the Parameter

A screenshot of a computer

AI-generated content may be incorrect.

A screenshot of a computer

AI-generated content may be incorrect.

This passes the value from P2_AMOUNT to the workflow’s parameter.














How Do I Make a Faceted Search Map Page in Oracle APEX

Combining faceted search with a map region in Oracle APEX enables users to filter data visually and spatially at the same time. This design ...