I’m trying to create a trigger that will associate an unique random string to every record inserted in a table.
So far I created a trigger, on before insert, that will generate and add the hash to the table. However, I’m wondering how should I go about ensuring this new hash is unique for my table.
So far I have the trigger below, but as you can see the uniques part is missing…
BEGIN
DECLARE newhash VARCHAR(255);
SELECT MD5(CONCAT(NOW(),RAND())) INTO newhash;
SET NEW.`hash` = newhash;
END
The column should be unique in the table definition and that’s it.
In any case, are you sure that you want md5(now || rand)? With reasonable implementations of now and rand, it’s highly unlikely that you are going to have duplicates, but if now() doesn’t have a lot of granularity or the random number is not a good random number, you could run into trouble under certain scenarios.
It might be a better idea to use an off-the-shelf scheme for this kind of things, such as using UUIDs (which MySQL seems to support: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid ).