MySQL roughly random string generation for updating rows

Ever wanted to inject hashes into existing rows of a MySQL database? The code below allows you to generate a different string for each row affected by the update and choose the random string’s length from 1 to 32 character.

I’m aware it’s not the most random of generators but for url hashes etc, it works well. Be sure to then check for duplicates, which are possible!

Change 20 to a length between 1 and 32.

Update the WHERE condition to suit your needs


UPDATE table_name
SET column_name = (
SELECT substring(MD5(RAND()), -20)
)
WHERE condition_column = 1;

Post a comment.