The Wayback Machine - https://web.archive.org/web/20240806220512/https://www.geeksforgeeks.org/plsql-statement-level-triggers/
Open In App

PL/SQL Statement level Triggers

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Statement-level triggers in Oracle databases execute actions for each transaction, responding to various database events like DML and DDL statements, system events, and user interactions. They act as programmed responses to specific table events, enhancing database management and automation.

Stored as named PL/SQL blocks, triggers execute automatically upon occurrence of a predefined event, crucial for efficient database operation.

In this article, we will cover PL/SQL Statement level Triggers syntax, their importance, characteristics, common use cases, and examples, illustrating their role in Oracle database management.

PL/SQL Statement Level Triggers

Statement-level triggers are said to be specialized PL/SQL code blocks that execute once per triggering DML statement like, Insert, Update, and Delete on any table. How about a glimpse of its structure?

Syntax:

CREATE [OR REPLACE] TRIGGER trigger_name //start
{BEFORE | AFTER } triggering_event
ON table_name
[FOLLOWS | PRECEDES another_trigger]
[ENABLE / DISABLE ]
[WHEN condition]
DECLARE
declaration statements
BEGIN
executable statements
EXCEPTION
exception_handling statements
END;

Importance of Statement-Level Triggers

*NOTE: Assume that you have created a database for some customers with constraints like, orders, sales etc.

  • Enforcement of Complex Data Rules: They can enforce complex data rules beyond what constraints can handle like deleting a customer’s entry in database and automatically removing their related orders.
  • Automation of Tasks: They tend to automate tasks based on database events (Insert, Update, Delete). Perhaps it can update a “total sales” table whenever a new order is placed, saving oneself, the time and effort to write a separate code to maintain accurate sales figures.
  • Centralization of Actions: They can centralize actions into reusable code blocks, making your code neat, easy to read & understand, and manage. One has to create multiple procedures that need to perform common actions like logging changes after inserting data into different tables. Instead of duplicating that code, one create a trigger that fires after any insert operation and performs the centralized logging action.
  • Enhanced Security: They can perform extra security checks and/or validate data to prevent unauthorized access or vulnerabilities. If a trigger could be set to fire before deleting a user account, then it could check if the user, attempting the deletion, has the necessary privileges to perform such an action.

Characteristics of Statement-Level Triggers

  • It can only be executed once per triggering DML statement.
  • For each row, clause is not present here.
  • It usually differs from row-level triggers that iterate per row.
  • Access to : old and: new pseudo records might be limited based on timing (Before or After).

Common Use Cases

  • It reduces code duplicacy and improves code maintainability.
  • It can log information about database modifications like user, timestamp, and table affected.
  • It tends to validate data and enforce rules beyond database constraints.
  • It can even add extra security checks before or after DML statements.

Example of PL/SQL Statement Level Triggers

Let us assume the same example. Suppose there exists a table named customers.

Example 1: Making An Audit Customer Update Trigger

Here, I made a trigger that fires or executes whenever there’s an update operation performed on the customers table. It tends to track changes made to customer information and record these changes in an audit table, named customer_audit.

CREATE OR REPLACE TRIGGER cust_update_audit
AFTER UPDATE ON customers
FOR EACH ROW
WHEN (NEW.name != OLD.name OR NEW.email != OLD.email OR NEW.phone != OLD.phone)
BEGIN
INSERT INTO customer_audit (customer_id, old_name, old_email, old_phone, new_name, new_email, new_phone, update_time)
VALUES (:OLD.customer_id, :OLD.name, :OLD.email, :OLD.phone, :NEW.name, :NEW.email, :NEW.phone, SYSDATE);
END;
/

Let us assume we have the following entry in the customers table.

Entry-in-the-table

Entry in the table

Query:

    UPDATE customers
SET name = 'GFG',
email = 'GFG@EMAIL.COM'
WHERE customer_id = 1;

Output:

Sample-output

Sample output

Explanation: The customer_audit table will now be updated with a new entry. But only the name will be changed, nothing else as per the above query or we can say, that, the trigger captures the old and new values of the updated customer and logs them into the customer_audit table.

Example 2: Making An Automatic Discount Trigger

Again I made a trigger that automatically applies a discount to a customer’s order if the total order amount exceeds a specified threshold. I set the threshold as $100 for now. Assume that we are using data from another table named Orders.

CREATE OR REPLACE TRIGGER order_discount
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
IF :NEW.order_total > 100 THEN
:NEW.order_total := :NEW.order_total * 0.9; -- Applying 10% discount
END IF;
END;
/
INSERT INTO orders (order_id, customer_id, order_total)
VALUES (1, 1, 120);

Output:

Updated-order-table

updated table

Explanation: Before the insertion query is executed, the trigger will check the order_total of the new order. But since the order_total (as per query, it is $120) exceeds $100, the trigger will apply a 10% discount. After trigger execution, the order_total for this order will be updated to $108. The orders table gets updated accordingly.

Conclusion

In Conclusion, PL/SQL Statement level Triggers are essential tools in Oracle database management, automating actions in response to specified events. Their syntax, importance, characteristics, and common use cases demonstrate their critical role in maintaining data integrity and enhancing security. Understanding and utilizing these triggers streamline database operations, ensuring efficiency and reliability in handling transactions and events.



Similar Reads

SQLite Triggers
SQLite is an embedded database that doesn't use a database like Oracle in the background to operate. It is written in C language and is used by developers who embed a lightweight database over the existing application, browser, or embedded systems. The main features of SQLite are that it is a tiny, quick, self-contained, reliable, full-featured SQL
9 min read
PL/SQL Triggers
PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features.PL/SQL supports SQL queries. It also supports the declaration of the variables, control statements, Functions, Records, Cursor, Procedure, and Triggers.PL/SQL contains a declaration section, execution section, and exception-handling section
6 min read
MariaDB Create Triggers
Triggers are a very useful and powerful feature of MariaDB. It is a database object associated with a table that activates if an INSERT, UPDATE or DELETE operations are performed. The name itself reflects their action as they run immediately without any human intervention when the respective operations are performed. In this article, you will learn
6 min read
Firebase Triggers
Firebase Triggers also known as Firebase Cloud Functions is backend development by offering serverless functions that respond to events from Firebase and Google Cloud services. These triggers enable developers to automate processes easily such as handling database changes, user authentication events, file uploads and more without managing servers.
5 min read
SELECT Statement in MariaDB
MariaDB uses SQL (Structured Query Language) and it is an open-source relational database management system (RDBMS) for managing and manipulating data. The SELECT statement is the most basic of all the SQL statements. It is essential to get data out of one or more database tables and display it. In this article, we will examine the syntax of the SE
3 min read
ORDER BY Statement in MariaDB
In MariaDB, the ORDER BY clause is an important component for organizing the result set of a query in a certain order. Being aware of the complexities of ORDER BY can significantly improve your capacity to get and evaluate data effectively, regardless of whether you're working with one or more columns, ascending or descending sorting, or both. This
3 min read
SQLite Replace Statement
SQLite is a database engine. It is a serverless architecture as it does not require any server to process queries. Since it is serverless, it is lightweight and preferable for small datasets. It is used to develop embedded software. It is cross-platform and available for various Operating systems such as Linux, macOS, Windows, Android, and so on. R
3 min read
SQLite Update Statement
SQLite is a database engine. It is a software that allows users to interact with relational databases, Basically, it is a serverless database which means it does not require any server to process queries. With the help of SQLite, we can develop embedded software without any configurations. SQLite is preferable for small datasets. Update StatementSo
3 min read
MariaDB INSERT Statement
MariaDB is a famous open-source relational database management system. It is renowned for its performance, scalability, and robust functions. One essential thing about operating with databases is the ability to insert information, and the INSERT statement plays a crucial role in this technique. In this article, we can explore the MariaDB INSERT dec
3 min read
SQL Server MERGE Statement
MERGE is a powerful SQL statement that allows you to perform INSERT/UPDATE/DELETE operations depending on the conditions you specify. It makes it easy to synchronize data between source and destination tables. This makes it efficient to handle data changes in one single statement. MERGE makes it easier to manage complex operations such as data ware
6 min read
Article Tags :
three90RightbarBannerImg