✏️ Oracle BEFORE UPDATE Trigger Tutorial

✏️ Oracle BEFORE UPDATE Trigger Tutorial

Before studying and practicing with all types of triggers, you must first create a scenario. Below are example schemas to follow before returning here to continue. Link: Click Here

This tutorial covers Oracle BEFORE UPDATE triggers, which execute automatically before an existing row is updated. They allow you to validate or modify data before the update occurs.


How to Use a BEFORE UPDATE Trigger in Oracle

A BEFORE UPDATE trigger in Oracle executes before any update

📘 Use Case

Whenever an order's status or amount is updated in the orders table, we want to log the old details in the orders_audit table before the change occurs.

🛠️ Trigger Code

CREATE OR REPLACE TRIGGER trg_before_order_update
BEFORE UPDATE OF status, amount ON orders
FOR EACH ROW
BEGIN
    INSERT INTO orders_audit (
        order_id,
        customer_id,
        product_id,
        deleted_by,
        deleted_date
    ) VALUES (
        :OLD.order_id,
        :OLD.customer_id,
        :OLD.product_id,
        'SYSTEM-UPDATE',
        SYSDATE
    );
END;

This trigger captures the old values before updating the status or amount fields and logs them for auditing purposes.

🧪 How to Test the Trigger

  1. Update an order:
UPDATE orders
SET status = 'SHIPPED', amount = 1600.00
WHERE order_id = 1005;
  1. Check the audit log:
SELECT * FROM orders_audit WHERE order_id = 1005;

Expected Result: A record is added to orders_audit showing the order’s original status and amount before the update.

📌 Benefits

  • Tracks changes to sensitive fields like status and amount.
  • Helps with rollback and audit in case of errors or disputes.
  • Improves data integrity and compliance.
oracle before update trigger, oracle audit before update, oracle logging trigger update, before update plsql trigger, order status update log trigger, oracle order table trigger, plsql update audit example

Now read the full article on BEFORE INSERTAFTER INSERTBEFORE UPDATEAFTER UPDATEBEFORE DELETE, and AFTER DELETE triggers in Oracle Database.

একটি মন্তব্য পোস্ট করুন