A Simple MySQL Trigger Example

I was searching for this a few days back and I was struck at how Google had all these terrible¬†explanations¬†at the top of the results. Here’s a simple way to create and understand triggers in mysql.

CREATE TABLE IF NOT EXISTS `emails` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `emails` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `emails_triggers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `emails` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

DELIMITER $$
CREATE TRIGGER trigger_test AFTER
INSERT ON emails
FOR EACH ROW
BEGIN
 INSERT INTO `emails_triggers` (email) values (NEW.email);
END$$
DELIMITER ;

insert into emails values('test@test.com');
select * from emails_trigger;

Just a note: the DELIMITER keyword is used via a tool like PhpMyAdmin or the MySQL Client. I could not get this keyword to be recognized by my SQL editor and had problems until I just pasted it via PhpMyAdmin.