generate random string in mysql

How to Generate Random String in MySQL

Sometimes you may need to generate random string in MySQL. There are several ways to do this in MySQL. In this article, we will learn how to create random string in MySQL.

How to Generate Random String in MySQL

One of the most common ways to generate random string in MySQL is to use UUID(). For example, if you want to generate an 8 character string, here’s a sample query for that.

SELECT LEFT(UUID(), 8);

UUID() function generates a 16-character string. Then we call LEFT() function to extract first 8 characters from it.

Alternatively, you can also use RAND() function to generate a random string.

SELECT LEFT(MD5(RAND()), 8)

In the above code, RAND() function returns a random number between 0 and 1 (excluding 1). This is passed to MD5() function which returns 128-bit checksum representation of the random string. Lastly, we call LEFT() function to retrieve the first left 8 characters.

In this article, we have learnt a couple of simple and fast ways to generate random string in MySQL. It is commonly required to generate keys, passwords, and other random strings in websites and applications.

Also read:

How to Import Excel File in MySQL
How to View MySQL Log File
How to Run MySQLdump Without Locking Tables
How to Check if MySQL Database Exists
How to Send Email from JavaScript

Leave a Reply

Your email address will not be published.