in SQL

MySQL roughly random string generation for inserting or updating rows

Ever wanted to inject hashes into new or existing rows of a MySQL database?

Two slightly different methods, but the same result…

Insert

The code below allows you to generate a different hash for each row you’re inserting. You can tweak to choose the string’s length. No unique checks are done.

INSERT INTO table_name (
column_name
) VALUES (
    (SUBSTRING(MD5(RAND()) FROM 1 FOR 20))
)

Update columns and values to suit your needs

Update

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 that suits your needs.

Update the WHERE condition to suit your needs

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

Work in a software agency where you struggle to delivery consistently to your unique clients and unique projects? I specialise in that challenge!

Follow me on X (formerly Twitter), Threads for insights, on Medium for thought pieces, or read about my agency focused workshops (UK only) for more information.

Share your thoughts

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.