Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random string in MySQL

Tags:

random

mysql

I'm trying to get a random string in phpmyadmin using a function. I have the following code:

CREATE FUNCTION randomPassword()
RETURNS varchar(128)
BEGIN

    SET @chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    SET @charLen = length(@chars);

    SET @randomPassword = '';

    WHILE length(@randomPassword) < 12
        SET @randomPassword = concat(@randomPassword, substring(@chars,CEILING(RAND() * @charLen),1));
    END WHILE;

    RETURN @randomPassword ;
END;

Now I get the error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5

Does anyone know how I can fix this?

like image 553
WillemKoonings Avatar asked Mar 10 '15 11:03

WillemKoonings


People also ask

How to generate random string in SQL?

If you need a string of random digits up to 32 characters for test data or just need some junk text to fill a field, SQL Server's NEWID() function makes this simple. NEWID() is used to create a new GUID (globally unique identifier), and we can use that as a base to get a string of random characters.

How to make unique id in MySQL?

UUID() function in MySQL. This function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”. It is designed as a number that is universally unique.

How can we get a random number between 1 and 100 in MySQL?

Random Integer RangeSELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for. SELECT FLOOR(RAND()*(25-10+1))+10; The formula above would generate a random integer number between 10 and 25, inclusive.


3 Answers

This is faster than concat + substring routine.

select substring(MD5(RAND()),1,20);

As I've tested inserting 1M random data, md5 routine consumes only 1/4 (even less) time of concat + substring routine;

The problem is a md5 string contains only 32 chars so if you need a longer one you'd have to manually generate more md5 strings and substring it yourself.

like image 177
Kim Avatar answered Oct 07 '22 08:10

Kim


Try this more simple solution:

SELECT CONV(FLOOR(RAND() * 99999999999999), 10, 36)
like image 38
Galma88 Avatar answered Oct 07 '22 08:10

Galma88


SELECT SUBSTRING(REPLACE(REPLACE(REPLACE( TO_BASE64(MD5(RAND())), '=',''),'+',''),'/',''), 2, 40)

This solution to generate a fixed length random string that contains all lower- and upper-case chars and digits.

SELECT SUBSTRING(REPLACE(REPLACE(REPLACE( TO_BASE64(MD5(RAND())), '=',''),'+',''),'/',''), 2, FLOOR(10+RAND()*31))

If you need a random length string (from 10 to 40 symbols in this example)

like image 3
Vladimir Borovsky Avatar answered Oct 07 '22 07:10

Vladimir Borovsky