You can use the update trigger to modify existing lines and the insert trigger to generate random numbers for new lines. In the body of the trigger, you generate a random number and check if it exists in the table. You do this in a loop and leave the loop as soon as you find a new (unique) number.
UPDATE trigger
DELIMITER // create trigger table1_before_update before update on table1 for each row begin declare rnd_num integer; loop1: loop set rnd_num := floor(rand() * 100000000); if not exists (select * from table1 where random_num = rnd_num) then set new.random_num = rnd_num; leave loop1; end if; end loop; end// DELIMITER ;
You can update all rows of the table:
update table1 set random_num = null where 1 = 1;
Note that the random_num column must be NULL. But it could be UNIQUE . So you can define it as random_num int null unique .
Since you only need to do this step once, you can remove this trigger.
INSERT trigger
DELIMITER // create trigger table1_before_insert before insert on table1 for each row begin declare rnd_num integer; loop1: loop set rnd_num := floor(rand() * 100000000); if not exists (select * from table1 where random_num = rnd_num) then set new.random_num = rnd_num; leave loop1; end if; end loop; end// DELIMITER ;
An INSERT trigger has the same body. When you insert new rows, you do not need to set the random_num column. The trigger will take care of this. It even works great with volume inserts:
insert into table1 (data) values ('data1'), ('data2'), ('data3'), ('data4'), ('data5');
Demo: http://rextester.com/ZIDG57947
Note that I use FLOOR(RAND() * 10) in the demo to demonstrate uniqueness over a small range. However - you should not try to insert more lines than the number of unique numbers possible :-)
With 20K lines and 100M possible unique numbers, a loop will be needed as 1.0002 (average) iterations per line.