Generate random string in MySQL

Have you ever wanted to generate a random string in MySQL, say for assigning a random password to a list of users? Well here is a useful tip!

[adsense:468x60:4496506397]

SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 6) AS password

This creates a 6 character (easy to change, as you can see) string where the characters are from the MD5 command (and therefore in the range a-z and 0-9).

[adsense:468x60:4496506397]

Comment Icon

8 Comments

The most recent comment was on Wed, 29th Jun 2011 - 08:51

Excellent tip - this would allow you to have a function for generating md5 keys for sessions instead of perl code... put it all in the db.

Thank for MYSQL random string generator help.

Really nice

Great tip!

For randomly assigned codes & passwords, we use a restricted alphabet that does not include vowels (or the digits 0 and 1 because they can resemble vowels). This is to avoid accidentally assigning a bad word, since virtually all bad words have at least one vowel.

Furthermore, our defaults are all uppercase.

Luckily we can slightly modify your tip with the mysql REPLACE and UPPER functions. Unfortunately, REPLACE doesn't seem to support regex and UPPER requires a call to CONVERT before it will work properly. So the code is a little convoluted, but it does seem to work fine...

SELECT UPPER(CONVERT(SUBSTRING(
  REPLACE(
    REPLACE(
      REPLACE(
        REPLACE(
          REPLACE(
            REPLACE(
              REPLACE(
                MD5(RAND())
              ,'1','')
            ,'0','')
          ,'a','')
        ,'e','')
      ,'i','')
    ,'o','')
  ,'u','')
FROM 1 FOR 6) USING latin1)) AS password

MD5 does not use a-z and 0-9, it uses a-f and 0-9 - only a range of 16 characters.

thanks for sharing

Very good, thank you very much !

thanks

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <img> <p>
  • You can use BBCode tags in the text. URLs will automatically be converted to links.
  • You can enable syntax highlighting of source code with the following tags: <code>, <pre>, <bash>, <css>, <html>, <js>, <jquery>, <mysql>, <php>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.