Question

I am pretty new to my RDBMS. Today I came across the topic TRIGGER in MySQL. Suppose if I have a table named person and another table named backup_person to store the deleted rows from the table person.

CREATE TABLE backup_person (
   `personID`         INT UNSIGNED  NOT NULL,
   `firstName`        VARCHAR(20)   NOT NULL,
   `lastName`         VARCHAR(20)   NOT NULL,
   `datetimeDeleted`  DATETIME      NOT NULL,
    PRIMARY KEY(`personID`)
);

I have the following trigger statements:

DELIMITER //
CREATE TRIGGER archiveEmployees
BEFORE DELETE ON person FOR EACH ROW
BEGIN
  INSERT INTO backup_person

  VALUES (OLD.personID, OLD.firstName, OLD.lastName, NOW());
END//

DELIMITER ;

Now the question is should I execute each time the above trigger before performing the delete statement: Eg:DELETE FROM persons WHERE firstName='Sabin' AND lastName = 'Jose';

or executing it once during creation of the table is sufficient?

Was it helpful?

Solution

A trigger is a mechanism that gets executed automatically from the DB every time the trigger condition is met.

In your case the trigger definition is BEFORE DELETE ON person. So every time before a delete on the table person occurs, the DB executes your trigger.

A Stored Procedure on the other hand is a function that you can call every time you like manually.

And another existing mechanism are Events. You can execute them on a time schedule you define i.e. every hour, automatically.

OTHER TIPS

The whole point of creating a trigger is that it's saved in the database and executed automatically when the specified event occurs. If you had to create the trigger every time you did a DELETE, you might as well just perform the INSERT itself.

So you just create it once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top