You can generate a random alphanumeric string with:
lpad(conv(floor(rand()*pow(36,8)), 10, 36), 8, 0);
You can use it in a BEFORE INSERT
trigger and check for a duplicate in a while loop:
CREATE TABLE `vehicles` (
`plate` CHAR(8) NULL DEFAULT NULL,
`data` VARCHAR(50) NOT NULL,
UNIQUE INDEX `plate` (`plate`)
);
DELIMITER //
CREATE TRIGGER `vehicles_before_insert` BEFORE INSERT ON `vehicles`
FOR EACH ROW BEGIN
declare str_len int default 8;
declare ready int default 0;
declare rnd_str text;
while not ready do
set rnd_str := lpad(conv(floor(rand()*pow(36,str_len)), 10, 36), str_len, 0);
if not exists (select * from vehicles where plate = rnd_str) then
set new.plate = rnd_str;
set ready := 1;
end if;
end while;
END//
DELIMITER ;
Now just insert your data like
insert into vehicles(col1, col2) values ('value1', 'value2');
And the trigger will generate a value for the plate
column.
(sqlfiddle demo)
That works this way if the column allows NULLs. If you want it to be NOT NULL you would need to define a default value
`plate` CHAR(8) NOT NULL DEFAULT 'default',
You can also use any other random string generating algorithm in the trigger if uppercase alphanumerics isn't what you want. But the trigger will take care of uniqueness.