Creating triggers to remove users
How do I create a trigger for my USERS table that means if one user is removed, that user is also taken out of the USERS_DIR table?

    Requires Free Membership to View

    When you register, my team of editors will also send you resources covering Linux administration and management; integration and interoperability between Linux, Windows and Unix; securing Linux and mixed-platform environments; and migrating to Linux.

    Margie Semilof, Editorial Director

    By submitting your registration information to SearchEnterpriseLinux.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchEnterpriseLinux.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

If you use the InnoDB storage engine, there is no need for a trigger. You can achieve the same effect using a foreign key with an appropriate cascading action:

ALTER TABLE users_dir ADD FOREIGN KEY (userId) REFERENCES users (userId) ON DELETE CASCADE;

If you use MyISAM or one of the other engines that does not yet enforce foreign key constraints, you can use a trigger:

CREATE TRIGGER users_AD AFTER DELETE ON users FOR EACH ROW DELETE FROM
users_dir WHERE userId = OLD.userId;

Note that the foreign key is defined on the users_dir table, but the trigger is defined on the users table.

The examples shown here for both foreign keys and triggers only address behavior if the user is deleted. You will need to decide what action to take if the user's id is updated to a different value instead.

This was first published in June 2007