Skip to content

Instantly share code, notes, and snippets.

@yogithesymbian
Created October 21, 2021 03:21
Show Gist options
  • Save yogithesymbian/698b27138a5ba89d2a32e3fc7ddd3cfb to your computer and use it in GitHub Desktop.
Save yogithesymbian/698b27138a5ba89d2a32e3fc7ddd3cfb to your computer and use it in GitHub Desktop.
generate auto number mysql before insert with unique logic concat with primary key
DELIMITER $$
DROP TRIGGER IF EXISTS `auto_number`$$
CREATE TRIGGER `auto_number` BEFORE INSERT on users
FOR EACH ROW BEGIN
SET new.auto_number = CONCAT(new.id, LEFT(UUID(), 8));
END$$
DELIMITER ;
@yogithesymbian
Copy link
Author

yogithesymbian commented Oct 21, 2021

other solution

SET new.auto_number = CONCAT(LAST_INSERT_ID(), LEFT(UUID(), 8));

i have thinking about the pk normaly is auto generate thats mean null .
if your unique number is not null on generate use SET new.auto_number = CONCAT(new.id, LEFT(UUID(), 8));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment