Writing a trigger to generate uuid in a table

If you never had a field containing uuid before in MySQL table, now you can add a new field default is null. Then create a trigger so that every time there’s a new record inserted, the uuid will be automatically generated for that row. Here’s how you write a trigger to add uuid to a field “user_api_key” in the table “api_users”

DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    TRIGGER `test`.`add uuid to api_users table` AFTER INSERT
    ON `test`.`api_users`
    FOR EACH ROW BEGIN
	IF new.user_api_key IS NULL THEN
	SET new.user_api_key =UUID();
	END IF;
    END$$

DELIMITER ;

If you run into this error, make sure you don’t duplicate the trigger.

This version of MySQL doesn’t yet support ‘multiple triggers with the same action time and event for one table.

To check for duplicate trigger, use this statement

SHOW TRIGGERS WHERE `table` = 'api_users';