MySQL trigger to update a field to the value of id

I don’t know of any way to do this in one statement, even using a trigger.

The trigger solution that @Lucky suggested would look like this in MySQL:

CREATE TRIGGER MyTrigger BEFORE INSERT ON MyTable
FOR EACH ROW BEGIN
  SET NEW.group_id = COALESCE(NEW.group_id, NEW.id);
END

However, there’s a problem. In the BEFORE INSERT phase, the auto-generated id value hasn’t been generated yet. So if group_id is null, it defaults to NEW.id which is always 0.

But if you change this trigger to fire during the AFTER INSERT phase, so you have access to the generated value of NEW.id, you can’t modify column values.

MySQL doesn’t support expressions for the DEFAULT of a column, so you can’t declare this behavior in the table definition either. *Update: MySQL 8.0.13 supports DEFAULT (<expression>) but the expression still can’t depend on an auto-increment value (this is documented).

The only solution is to do the INSERT, and then immediately do an UPDATE to change the group_id if it’s not set.

INSERT INTO MyTable (group_id, value) VALUES (NULL, 'a');
UPDATE MyTable SET group_id = COALESCE(group_id, id) WHERE id = LAST_INSERT_ID();

Leave a Comment