Create Trigger PL SQL Example Best Practices

Creating triggers in PL/SQL (Procedural Language/Structured Query Language) is a powerful way to automate database operations and maintain data integrity. Triggers are PL/SQL procedures that are automatically executed when a specific event occurs on a table. Today, we'll explore how to create triggers in PL/SQL with detailed examples.

What is a SQL Trigger? - Essential SQL
What is a SQL Trigger? - Essential SQL

Before diving into examples, let's clarify the basics. A PL/SQL trigger consists of three main parts: a header that defines the trigger, a body that contains the PL/SQL code, and an optional specification of the trigger's properties like when it fires (before or after an event).

PL/SQL tutorial 18: DDL Trigger with Schema Auditing Example
PL/SQL tutorial 18: DDL Trigger with Schema Auditing Example

Creating Simple Triggers

Let's start with a simple trigger. Suppose we have an 'employees' table and we want to create a trigger that prints a message whenever a new row is inserted into the table.

PL/SQL tutorial 24: How To Create INSTEAD OF DELETE trigger in Oracle Database
PL/SQL tutorial 24: How To Create INSTEAD OF DELETE trigger in Oracle Database

Here's how you can create such a trigger:

```sql CREATE OR REPLACE TRIGGER print_hello AFTER INSERT ON employees FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE('Hello from the trigger!'); END; ```

Understanding Trigger Components

PL/SQL tutorial 21: How To Create Startup Trigger In Oracle Database By Manish Sharma
PL/SQL tutorial 21: How To Create Startup Trigger In Oracle Database By Manish Sharma

In the above example, let's break down the components:

- `CREATE OR REPLACE TRIGGER`: This clause creates a new trigger or replaces an existing one. - `print_hello`: This is the trigger's name. - `AFTER INSERT ON employees`: This specifies that the trigger should fire after an insert operation on the 'employees' table. - `FOR EACH ROW`: This indicates that the trigger should be executed once for each row affected by the triggering event. - `DBMS_OUTPUT.PUT_LINE('Hello from the trigger!')`: This is the PL/SQL code that gets executed when the trigger fires.

Testing the Trigger

Now, let's insert a row into the 'employees' table and see our trigger in action:

MySQL Triggers: How to Automate Data Integrity
MySQL Triggers: How to Automate Data Integrity

```sql INSERT INTO employees (id, name) VALUES (1, 'John Doe'); ```

After this insert operation, you should see the message 'Hello from the trigger!' printed in your Oracle SQL Developer or SQL*Plus output window.

Creating Triggers with Conditions

Sometimes, we might want to create triggers that only fire under certain conditions. Let's modify our previous trigger to only print the message when the inserted row's 'name' is 'John Doe'.

a red and white sign with the words pl / sol on it's side
a red and white sign with the words pl / sol on it's side

Adding CONDITION Clause

The `IF CONDITION` clause allows us to specify conditions under which the PL/SQL code in the trigger body will be executed. Here's how we can modify our trigger:

7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
CRUD in SQL: Unleashing the Power of Seamless Data Manipulation
CRUD in SQL: Unleashing the Power of Seamless Data Manipulation
a cell phone with the text postgresql and other information on it
a cell phone with the text postgresql and other information on it
SQL in 60 days
SQL in 60 days
Triggers in SQL | Triggers In Database | SQL Triggers Tutorial For Beginners | Edureka Rewind
Triggers in SQL | Triggers In Database | SQL Triggers Tutorial For Beginners | Edureka Rewind
SQL Triggers with Examples
SQL Triggers with Examples
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
an info poster showing the different types of web pages and how they are used to create them
an info poster showing the different types of web pages and how they are used to create them
SQL Basics For Beginners
SQL Basics For Beginners
Learn SQL just by investing 30 minutes a day within 30 Days
Learn SQL just by investing 30 minutes a day within 30 Days
SQL Sheatsheet! 👍
SQL Sheatsheet! 👍
SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL Query Execution Order
SQL Query Execution Order
SQL Cheatsheet In 2026 🚀
SQL Cheatsheet In 2026 🚀
CQF - SQL
CQF - SQL
SQL IN NUTSHELL
SQL IN NUTSHELL
SQL - Using like operator and escape character
SQL - Using like operator and escape character

```sql CREATE OR REPLACE TRIGGER print_hello AFTER INSERT ON employees FOR EACH ROW BEGIN IF INSERTING AND :NEW.name = 'John Doe' THEN DBMS_OUTPUT.PUT_LINE('Hello from the trigger!'); END IF; END; ```

In this example, the trigger will only print the message if a new row is being inserted and the 'name' of the new row is 'John Doe'.

Testing the Conditional Trigger

Try inserting a row with a different name, like 'Jane Doe', and you'll see that the trigger doesn't fire. However, if you insert 'John Doe', the trigger will execute as expected.

Handling Trigger Errors

In some cases, the PL/SQL code in a trigger might raise errors. In such situations, we can use the `WHEN OTHERS` clause to handle these errors.

Implementing Error Handling

Let's enhance our trigger to handle any errors that might occur:

```sql CREATE OR REPLACE TRIGGER print_hello AFTER INSERT ON employees FOR EACH ROW DECLARE l_no_data EXCEPTION; BEGIN IF INSERTING AND :NEW.name = 'John Doe' THEN DBMS_OUTPUT.PUT_LINE('Hello from the trigger!'); END IF; WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLCODE || ' - ' || SQLERRM); END; ```

In this version of the trigger, if an error occurs (for example, if there's no data to insert), the trigger will print an error message with the error code and message.

Testing Error Handling

Try inserting a row with no data and you'll see that the error is gracefully handled by our trigger.

In conclusion, creating triggers in PL/SQL can greatly enhance the functionality of your database and help automate various tasks. By understanding the basic syntax and structure of triggers, you can create sophisticated triggers to maintain data integrity and automate database operations.

Remember, the key to efficient trigger creation lies in understanding your requirements and carefully crafting your triggers to suit your needs. Happy coding!

Related Articles

Grouping Sets Query Sql Insert Into Values Example Sql Function Return Multiple Values Can You Do Two Inner Joins In Sql Microsoft Sql Server Management Studio Query Optimizer Grouping Sets Sql Syntax Can Sql Function Return Multiple Values What Is Create Trigger In Sql Create Trigger Pl Sql Example Drop Trigger Sql Server Example