1

I have never written a trigger before and I am following a tutorial http://net.tutsplus.com/tutorials/databases/introduction-to-mysql-triggers/ but I am confused about something.

I am trying to write a trigger which pulls data from a table AFTER INSERT and logs it in a history table. Here's my code so far:

DELIMITER $$

CREATE TRIGGER trackHistory
AFTER INSERT ON test.inventory
FOR EACH ROW BEGIN
***
END;

DELIMITER ;

I need to add a INSERT INTO history... query, but I don't understand how I reference the fields on the correct row of the 'inventory' table. Will the answer be the same for and UPDATE or DELETE?

EDIT: I have tried to follow the advice of the answer below, but it didn't work I got this error

1363 - There is no OLD row in on INSERT trigger. Whats wrong?

DELIMITER $$

CREATE TRIGGER trackInsertHistory
AFTER INSERT ON inventory
FOR EACH ROW BEGIN
    INSERT INTO history
    VALUES (NEW.ID, OLD.Quantity, NEW.Quantity, TIMESTAMP);
END$$

CREATE TRIGGER trackStockHistory
AFTER UPDATE ON inventory
FOR EACH ROW BEGIN
    INSERT INTO history
    VALUES (NEW.ID, OLD.Quantity, NEW.Quantity, TIMESTAMP);
END$$

DELIMITER ;
5
  • only the NEW record is there on an INSERT. For an UPDATE, the NEW record holds the 'new' values, and the OLD record holds the 'old' values. Commented Aug 12, 2013 at 19:15
  • Oh, of course. So, what I really want to do on the after insert update is set both 'old_quantity' and 'new_quantiy' on the table to be NEW.Quantity. Thanks again! Commented Aug 12, 2013 at 19:20
  • Interesting... I got this error now #1235 - This version of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table'... I guess I just need to do this in two separate queries? Commented Aug 12, 2013 at 19:22
  • that would be the safe way :) Commented Aug 12, 2013 at 19:30
  • 1
    Maybe you should add to the HISTORY what type of update it was (Insert, Update) ... or, could just be inferred when old=new Commented Aug 12, 2013 at 19:31

2 Answers 2

2

they are referenced as NEW and OLD.

NEW is the new record to be inserted or the updated data.

OLD is the deleted record, or the old data before an update.

Sign up to request clarification or add additional context in comments.

1 Comment

I just made an edit, I can't figure out how to follow your advice. Please advise.
2

In an INSERT trigger, only NEW.col_name can be used; there is no old row. In a DELETE trigger, only OLD.col_name can be used; there is no new row. In an UPDATE trigger, you can use OLD.col_name to refer to the columns of a row before it is updated and NEW.col_name to refer to the columns of the row after it is updated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.