Master PL SQL Trigger Before Insert Example Guide

When dealing with databases, managing data integrity and consistency can be a daunting task. One powerful tool that can simplify this process is a PL/SQL trigger, particularly one defined with the BEFORE INSERT event. PL/SQL (Procedural Language/Structured Query Language) is a procedural extension to SQL used in Oracle Database. Let's explore how to create a PL/SQL trigger on the BEFORE INSERT event, ensuring the data being inserted meets your desired criteria.

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

Before we dive into creating a trigger, it's essential to understand that a PL/SQL trigger is a set of PL/SQL statements that are automatically executed when a specified event occurs on a specific table. In this case, the event is 'BEFORE INSERT', meaning our trigger will fire whenever a new row is about to be inserted into the specified table.

INSTEAD OF INSERT Triggers in SQL Server Example
INSTEAD OF INSERT Triggers in SQL Server Example

Creating a Simple PL/SQL Trigger for BEFORE INSERT

Let's begin by creating a simple trigger that logs every insert operation on a table named 'EMPLOYEES'. The trigger will record the operation type, the table name, the old and new values, and the timestamp.

PL/SQL tutorial 15: DML Trigger With Before Insert, Update and Delete DML Examples
PL/SQL tutorial 15: DML Trigger With Before Insert, Update and Delete DML Examples

The trigger will look something like this:

```sql CREATE OR REPLACE TRIGGER log_insert_before BEFORE INSERT ON employees FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE('Operation type: INSERT, Table name: EMPLOYEES'); DBMS_OUTPUT.PUT_LINE('Old value: '); DBMS_OUTPUT.PUT_LINE('New value: ' || :NEW.employee_id || ', ' || :NEW.first_name || ', ' || :NEW.last_name); DBMS_OUTPUT.PUT_LINE('Timestamp: ' || SYSDATE); END log_insert_before; ```

Understanding the Trigger Structure

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

The trigger is created using the 'CREATE OR REPLACE TRIGGER' command. The 'BEFORE INSERT' clause specifies that the trigger should fire before an INSERT operation. The 'ON employees' clause designates the table on which the trigger should operate. The 'FOR EACH ROW' clause indicates that the trigger should execute once for each row being inserted into the table.

Inside the trigger, we use the 'DBMS_OUTPUT.PUT_LINE' procedure to print our logging information. We use the special ':' prefix and 'NEW' keyword to refer to new values for each column in the inserted rows.

Using the Trigger

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

Once the trigger is created, you can use it by performing an INSERT operation on the 'EMPLOYEES' table. For example:

```sql INSERT INTO employees (employee_id, first_name, last_name) VALUES (1, 'John', 'Doe'); ```

After executing this INSERT statement, you should see log messages printed to the console, detailing the insert operation.

Implementing Business Logic with BEFORE INSERT Triggers

SQL Triggers
SQL Triggers

Beyond simple logging, BEFORE INSERT triggers can also enforce business rules and constraints. For instance, you could ensure that a new employee's salary is never less than the minimum wage, or that duplicate emails are not added to the system.

Enforcing a Minimum Salary

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
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
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 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
SQL in 60 days
SQL in 60 days
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
SQL - Using like operator and escape character
SQL - Using like operator and escape character
CQF - SQL
CQF - SQL
SQL IN NUTSHELL
SQL IN NUTSHELL
an image of a diagram with the words,'the sq circle'in different languages
an image of a diagram with the words,'the sq circle'in different languages
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
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
a diagram showing the different types of commands
a diagram showing the different types of commands
7 SQL Commands Every Beginner Must Know
7 SQL Commands Every Beginner Must Know
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 Cheatsheet In 2026 🚀
SQL Cheatsheet In 2026 🚀
SQL Sheatsheet! 👍
SQL Sheatsheet! 👍

Let's create a trigger that ensures no employee's salary is less than $30,000. If an Insert operation attempts to violate this rule, the trigger will rollback the operation and print an error message:

```sql CREATE OR REPLACE TRIGGER enforce_min_salary BEFORE INSERT ON employees FOR EACH ROW DECLARE min_salary CONSTANT NUMBER(8,2) := 30000; BEGIN IF :NEW.salary < min_salary THEN RAISE_APPLICATION_ERROR( -20001, 'Salary must be greater than or equal to ' || min_salary ); END IF; END enforce_min_salary; ```

In this trigger, we use the 'RAISE_APPLICATION_ERROR' procedure to throw an error when the inserted salary is less than the minimum.

Ensuring Unique Emails

To prevent duplicate emails, you could create a trigger that checks if the email address already exists in the table. If it does, the trigger can rollback the operation and print an error message:

```sql CREATE OR REPLACE TRIGGER enforce_unique_emails BEFORE INSERT ON employees FOR EACH ROW DECLARE email_exist NUMBER; BEGIN SELECT COUNT(*) INTO email_exist FROM employees WHERE email = :NEW.email; IF email_exist > 0 THEN RAISE_APPLICATION_ERROR( -20002, 'Email address must be unique' ); END IF; END enforce_unique_emails; ```

Here, we use a 'SELECT COUNT(*)' statement to check if the email address already exists in the table.

In conclusion, PL/SQL triggers on the BEFORE INSERT event provide a powerful tool to manage data integrity and enforce business rules in your Oracle Database. By harnessing their power, you can create robust and reliable database schemas that reflect your unique business needs. The sky's the limit when it comes to the creative application of these triggers, so go forth and script away!

Related Articles

Insert Values Sql Query Drop Trigger Sql Statement Grouping Sets Sql Example Grouping Sets In Sql Server With Example Can You Have Multiple Inner Joins In Sql Sql Find Duplicate Values In Multiple Columns Sql Trigger Example Insert Multiple Values Sql Query Why Triggers Are Used In Sql Difference Between Microsoft Sql Server Management Studio And Mysql