EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

SQL AFTER UPDATE Trigger

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » SQL Tutorial » SQL AFTER UPDATE Trigger

SQL AFTER UPDATE Trigger

Introduction to SQL AFTER UPDATE Trigger

AFTER UPDATE Trigger in SQL is a stored procedure on a database table that gets invoked or triggered automatically after an UPDATE operation gets successfully executed on the specified table. For uninitiated, the UPDATE statement is used to modify data in existing rows of a data table. The AFTER UPDATE trigger is helpful in scenarios where we want to record the time of status change or record changes in the rating field based on the modification in values of some other field etc. It basically helps us in logging, auditing, and tracking changes.

Syntax

The basic syntax for writing SQL AFTER UPDATE Trigger in SQL is as follows :

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CREATE TRIGGER [schema_name. ] trigger_name ON table_name
AFTER UPDATE
AS
BEGIN
[SET NOCOUNT {ON/OFF}] {SQL statements}
END

Parameters

The parameters used in the above-mentioned syntax are as follows :

schema_name: This is the name of the schema in which we will be creating the new trigger. You may ignore it as a schema name is optional. By default, triggers will be created in the schema you are currently working in.

trigger_name: This is the name of the trigger which you want to create.

table_name: This is the name of the table to which the trigger will be applied.

SQL statements: SQL statements form the body of the trigger. These are a set of SQL operations that will be performed once the AFTER UPDATE trigger is invoked.

Examples to Implement SQL AFTER UPDATE Trigger

let us try a few examples to understand it in detail:

Popular Course in this category
Sale
SQL Training Program (7 Courses, 8+ Projects)7 Online Courses | 8 Hands-on Projects | 73+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (8,906 ratings)
Course Price

View Course

Related Courses
JDBC Training (6 Courses, 7+ Projects)PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

In order to illustrate the functionality of the AFTER UPDATE trigger, let us create a dummy table called “books_audit_table”. This table contains details pertaining to books available in a library. We can use the following code snippet to create the said table.

Code:

CREATE TABLE books_audit_table (
book_id INT NOT NULL IDENTITY PRIMARY KEY,
title VARCHAR(100)  NOT NULL,
author_name  VARCHAR(100),
genre VARCHAR(100),
updated_at DATETIME,
status VARCHAR(100)
);

Output:

books audit table

The query returned successfully. Next, using the following INSERT query insert a few records in the table to work with.

Code:

INSERT INTO [practice_db].[dbo].[books_audit_table] ([title] ,[author_name] ,[genre] ,[updated_at] ,[status])
VALUES
('The Choice','Edith Eva Eger','Memoir',NULL, NULL),
('Deep Work','Carl Newport','Self Help',NULL, NULL),
('A Man Called Ove','Fredrik Backman','Fiction',NULL, NULL),
('When Breath Becomes Air','Paul Kalanithi','Memoir',NULL, NULL),
('Man Search for Meaning','Viktor Frankl','Memoir',NULL, NULL),
('The Third Pillar','Raghuram Rajan','Economics',NULL, NULL)
GO

Output:

records

we have successfully created the “books_audit_table”. Now we are all set to try a few examples based on the AFTER UPDATE trigger.

Example #1

Step 1: Create a trigger in SQL, which automatically updates the date and time of borrowing a book from the collection.

Code:

CREATE TRIGGER update_trigger ON books_audit_table
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE books_audit_table set updated_at = GETDATE()
from books_audit_table b
INNER JOIN inserted i on b.book_id=i.book_id
AND i.status = 'Borrowed'
END
GO

Output:

Create a trigger in SQL

Step 2: The query has successfully created the update_trigger. We can check the newly created trigger in the object explorer.

object explorer

Step 3: Now, let us update the status of the first book to ‘Borrowed’ using the following statement.

Code:

UPDATE books_audit_table
SET Status='Borrowed'
WHERE book_id = 1;

Output:

status of the first book

Step 4: Since the update query was successful, update_trigger must have been automatically invoked and the updated_at column must have been automatically populated with the current timestamp. The following select query can be used to check the same.

Code:

SELECT * FROM books_audit_table;

Output:

current timestamp

Step 5: We can observe in the image that for book_id = 1, the updated_at column has been populated. Let us try one more example based on the same concept. This time let us do it for book_id = 5.

Code:

UPDATE books_audit_table
SET Status='Borrowed'
WHERE book_id = 5;

Output:

SQL AFTER UPDATE Trigger7

Step 6:

SQL AFTER UPDATE Trigger8

Explanation: Here as well, the update_trigger got automatically invoked and the updated_at column is updated to the current timestamp.

Example #2

Suppose two new columns such as borrowed_at and returned_at have been added to the books_audit_table. These columns have to be populated with a timestamp when the status of the book changes to “Borrowed” or “Returned”.

Step 1: You may use the following ALTER statements to modify the table.

Code:

ALTER TABLE books_audit_table
DROP COLUMN updated_at;
ALTER TABLE books_audit_table
ADD borrowed_at DATETIME;
ALTER TABLE books_audit_table
ADD returned_at DATETIME;

Output:

modify the table

Step 2: The modified table looks something as follows:

SQL AFTER UPDATE Trigger10

Step 3: Next, let us create an after update trigger called “update_trigger_new” using the following query.

Code:

CREATE TRIGGER update_trigger_new ON books_audit_table
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE books_audit_table set borrowed_at = GETDATE()
FROM books_audit_table b
INNER JOIN inserted i on b.book_id=i.book_id
AND i.status = 'Borrowed'
UPDATE books_audit_table set returned_at = GETDATE()
FROM books_audit_table b
INNER JOIN inserted i on b.book_id=i.book_id
AND i.status = 'Returned'
END
GO

Output:

SQL AFTER UPDATE Trigger11

The trigger has been successfully created. It can be seen in the object explorer.

SQL AFTER UPDATE Trigger12

Step 4: Next, let us update the status of book_id 3 to “Returned ”.

Code:

UPDATE books_audit_table
SET Status='Returned'
WHERE book_id = 3;

Output:

SQL AFTER UPDATE Trigger13

SQL AFTER UPDATE Trigger14

Step 5: The highlighted row shows the changes made by the update query and the trigger. It’s fun right. Let us try the following update query.

Code:

UPDATE books_audit_table
SET status = 'Returned'
WHERE book_id = 1;

Output:

SQL AFTER UPDATE Trigger15

SQL AFTER UPDATE Trigger16

Explanation: Wow, all the necessary changes have been made by the trigger.

Conclusion

AFTER UPDATE Trigger is a kind of trigger in SQL that will be automatically fired once the specified update statement is executed. It can be used for creating audit and log files which keep details of last update operations on a particular table.

Recommended Article

This is a guide to SQL AFTER UPDATE Trigger. Here we discuss an introduction to SQL AFTER UPDATE Trigger, examples for better understanding. You can also go through our other related articles to learn more –

  1. PostgreSQL GRANT
  2. PostgreSQL if else
  3. Cursors in PostgreSQL
  4. Triggers in SQL

SQL Training Program (7 Courses, 8+ Projects)

7 Online Courses

8 Hands-on Projects

73+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Advanced
    • SQL Formatter
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Server Versions
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
    • SQL Super Key
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL Window Functions
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite?functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL MOD()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Server Permission
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ADD Column
    • SQL Ranking Function
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • NoSQ
    • NoSQL Databases List
    • NoSQL Injection
    • NoSQL vs SQL Databases
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - SQL Training Program (7 Courses, 8+ Projects) Learn More