Skip navigation

The easiest way I’ve found to generate a random alphanumeric string involves RAND(), SHA(), and TO_BASE64()

select LEFT( TO_BASE64( SHA(rand()) ), 6 ) ;

You need MySQL 5.6 to execute.

Alternatively some MYSQL Procedures magic

DELIMITER //

drop function if exists randChr //
create function randChr()
returns char
BEGIN
  IF RAND() <= 0.5 THEN -- Lowercase
	return CHAR( 97 + 25*rand() ) ;
  ELSE -- uc
    return CHAR( 65 + 25*rand() ) ;
  END IF;
END //

drop function if exists randString //
create function randString( len int )
returns varchar(255)
BEGIN
  SET @n = 0;
  SET @res = '' ;
  REPEAT
    SET @res = concat( @res, randChr() ) ;
    set @n = @n + 1 ;
  UNTIL @n >= len END REPEAT;
  return @res ;
END //

DELIMITER ;

select randString( 5 );
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: