Concatenating a string and primary key Id while inserting

If user_id is an AUTO_INCREMENT primary key, then you can’t do this with a single statement, even if you use a trigger.

The problem is that the AUTO_INCREMENT value isn’t generated until after the BEFORE INSERT trigger runs, but you can’t change username in the AFTER INSERT trigger.

So you just have to do the INSERT, then immediately do an UPDATE.

If user_id is not an AUTO_INCREMENT, but instead is something you specify yourself, then it’s easy, you just do the concatenation in your PHP code before you pass the values as parameters.


Update: You can’t do it with MySQL 5.7 generated columns either. It results in this error when you try to create the table:

Generated column ‘username’ cannot refer to auto-increment column.

Leave a Comment