SQL Trigger Example Insert Update Tutorial With Code

SQL triggers are powerful database features that automate specified actions when specific events occur. Common events include INSERT, UPDATE, and DELETE operations on a table. Today, we'll be exploring practical examples of creating SQL triggers on INSERT and UPDATE events, focusing on the Microsoft SQL Server (MSSQL) syntax.

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

Before we dive into the examples, let's briefly understand why we use triggers. In simple terms, triggers help us enforce complex business rules, maintain data integrity, and automate tasks that would otherwise require manual processing.

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

INSERT Triggers

INSERT triggers fire when a new row is inserted into a table. They are beneficial for updating related tables, checking for duplicate values, or performing calculations and aggregations based on the inserted data.

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

Here's a simple example of an INSERT trigger in MSSQL. This trigger updates a 'LastActivity' field in the 'Customers' table whenever a new row is inserted into the 'Orders' table:

```sql CREATE TRIGGER tr_Orders_AfterInsert ON Orders AFTER INSERT AS BEGIN UPDATE Customers SET LastActivity = GETDATE() WHERE CustomerID IN (SELECT CustomerID FROM inserted); END; ```

Inserted Virtual Table

SQL Triggers
SQL Triggers

The inserted system table is a virtual table containing the rows that were inserted and can be used within the trigger to access the newly inserted data. As shown in our example, it's useful for checking specific conditions or updating related rows.

Let's consider another example. Suppose we have an 'Employees' table with an 'EmployeeID' column. We want to enforce a unique constraint on the 'Email' column and throw an error message if a duplicate email is inserted. Here's how we can do it:

```sql CREATE TRIGGER tr_Employees_BeforeInsert ON Employees BEFORE INSERT AS BEGIN IF EXISTS (SELECT 1 FROM Employees WHERE Email = (SELECT Email FROM inserted)) BEGIN RAISERROR('Duplicate email not allowed.', 16, 1); ROLLBACK; END END; ```

Inserted or Deleted Virtual Table

SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide

In certain cases, you might want to check the old and new values when a row is updated. Here, we can use both the inserted and deleted virtual tables. For instance, you want to keep track of the old and new values of 'Salary' for each 'Employee' when the row is updated:

```sql CREATE TRIGGER tr_Employees_AfterUpdate ON Employees AFTER UPDATE AS BEGIN INSERT INTO SalaryHistory (EmployeeID, OldSalary, NewSalary) SELECT EmployeeID, (SELECT Salary FROM deleted), (SELECT Salary FROM inserted) WHERE EXISTS (SELECT 1 FROM deleted WHERE Salary != (SELECT Salary FROM inserted)); END; ```

UPDATE Triggers

UPDATE triggers fire when one or more existing rows are updated in a table. They are handy for maintaining referential integrity, updating related tables, or logging changes.

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

Let's consider an 'Orders' and 'OrderDetails' table scenario. Whenever an 'Order' status is updated, we want to update the 'IsShipped' field in the 'OrderDetails' table based on the new 'OrderStatus' value:

```sql CREATE TRIGGER tr_Orders_AfterUpdate ON Orders AFTER UPDATE AS BEGIN UPDATE OrderDetails SET IsShipped = CASE WHEN OrderStatus = 'Shipped' THEN 1 ELSE 0 END WHERE OrderID = (SELECT OrderID FROM inserted); END; ```

As shown in the examples, both INSERT and UPDATE triggers can streamline database management, enhance data integrity, and automate complex business rules. It's crucial to thoroughly test triggers to prevent unintended side effects and performance issues. Happy coding!

Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
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
Save This SQL Commands Cheat Sheet Before Your DBMS Exam! 💻📚
Save This SQL Commands Cheat Sheet Before Your DBMS Exam! 💻📚
CQF - SQL
CQF - SQL
SQL in 60 days
SQL in 60 days
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
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
7 SQL Commands Every Beginner Must Know
7 SQL Commands Every Beginner Must Know
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
CRUD in SQL: Unleashing the Power of Seamless Data Manipulation
CRUD in SQL: Unleashing the Power of Seamless Data Manipulation
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 Joins Short Notes, Essential Sql Commands, Understanding Sql Operators, Sql Join Statement Code, How To Avoid Sql Errors, Troubleshooting Sql Commands, Advanced Sql Queries, How To Avoid Sql Server Errors, Javascript Call Stack Diagram
Sql Joins Short Notes, Essential Sql Commands, Understanding Sql Operators, Sql Join Statement Code, How To Avoid Sql Errors, Troubleshooting Sql Commands, Advanced Sql Queries, How To Avoid Sql Server Errors, Javascript Call Stack Diagram
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
SQL Cheatsheet — Learn the Basics Fast New to databases? Here’s a quick SQL cheatsheet with the most-used commands: SELECT, INSERT, UPDATE, DELETE, and more. Perfect for beginners and a great refresh for pros! #SQLCheatsheet #LearnSQL #DatabaseBasics #SQLCommands #CodingForBeginners #BackendTips #DevTools #TechCheatsheet #QueryLikeAPro #SQLTips #savageslayer #programbereach #sohaibalikhan #sohaibbashirkhan #researchteq #savageslayerofficials #datawarlord #datawarlordofficial #wordpressdevelop... Handy Sql Scripts, Sql Code With Comments, Sql Tables With Examples, Sql Case Statement Tutorial, Sql Database Code Example, Sql Notes, Sql Database Code And Text, Sql Aesthetic, Sql Cheat Sheet
SQL Cheatsheet — Learn the Basics Fast New to databases? Here’s a quick SQL cheatsheet with the most-used commands: SELECT, INSERT, UPDATE, DELETE, and more. Perfect for beginners and a great refresh for pros! #SQLCheatsheet #LearnSQL #DatabaseBasics #SQLCommands #CodingForBeginners #BackendTips #DevTools #TechCheatsheet #QueryLikeAPro #SQLTips #savageslayer #programbereach #sohaibalikhan #sohaibbashirkhan #researchteq #savageslayerofficials #datawarlord #datawarlordofficial #wordpressdevelop... Handy Sql Scripts, Sql Code With Comments, Sql Tables With Examples, Sql Case Statement Tutorial, Sql Database Code Example, Sql Notes, Sql Database Code And Text, Sql Aesthetic, Sql Cheat Sheet
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 Joins Explained with Examples | Beginner SQL Guide
SQL Joins Explained with Examples | Beginner SQL Guide
SQL Cheatsheet In 2026 🚀
SQL Cheatsheet In 2026 🚀

Related Articles

Can You Do Multiple Joins In Sql Sql Find Duplicate Values In Multiple Columns What Is Grouping Sets In Sql Grouping Sets Query Mysql Vs Microsoft Sql Server Management Studio Grouping Sets Sql Syntax Sql Insert Into Values Example W3schools Multiple Joins Microsoft Sql Server Management Studio Query Builder Apex List Of Values Sql Query