SQLite Trigger: AFTER UPDATE

It specifies how to create trigger after update the data. Suppose, we have two tables COMPANY and AUDIT, here we want to keep audit trial for every record being updated in COMPANY table.

COMPANY table:

snippet
CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Create a new table named AUDIT where log messages will be inserted whenever there is an updation in COMPANY table.

AUDIT table:

snippet
CREATE TABLE AUDIT(
    EMP_ID INT NOT NULL,
    ENTRY_DATE TEXT NOT NULL
);

CREATE trigger after update:

Use the following syntax to create a trigger named "after_up" on COMPANY table after update operation.

snippet
CREATE TRIGGER after_up AFTER UPDATE 
ON COMPANY
BEGIN
INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now'));
END;
Sqlite Trigger after update 1

Now update the old record as following:

snippet
UPDATE COMPANY SET ADDRESS = 'Noida' WHERE ID = 1;
Sqlite Trigger after update 2

See the result:

Sqlite Trigger after update 3

See the trigger:

snippet
SELECT name FROM sqlite_master
WHERE type = 'trigger';
Sqlite Trigger after update 4

SQLite Trigger: BEFORE UPDATE

If you want to create the trigger before updating the data:

snippet
CREATE TRIGGER befor_up BEFORE UPDATE 
ON COMPANY
BEGIN
INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now'));
END;
Sqlite Trigger after update 5

See the triggers:

snippet
SELECT name FROM sqlite_master
WHERE type = 'trigger';
Sqlite Trigger after update 6
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents