Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random chars and insert with MySQL? [duplicate]

Tags:

sql

mysql

Duplicate:
Inserting random characters to MYSQL Database

How can I generate 100 records with 5 random characters and insert into the database with a query.

I want to insert into this table:

codes
  id (auto-increment)
  codes
like image 540
spotlightsnap Avatar asked Nov 21 '11 04:11

spotlightsnap


People also ask

How do I generate a random character in MySQL?

In order to generate a 10 character string, we can use inbuilt functions 'rand()' and 'char()'.

How do I generate a random key in SQL?

SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

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.

How do you generate unique strings in SQL Server?

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.


2 Answers

Try this one -

SELECT CONCAT(
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25))),
  CHAR( FLOOR(65 + (RAND() * 25)))
  ) random_string;

This query generates ASCII codes from 'A' to 'Z' and generates a random string from them. I cannot say that this way is elegant, but it works;-)

like image 103
Devart Avatar answered Nov 08 '22 23:11

Devart


INSERT INTO codes_tbl (codes) VALUES (SUBSTRING(MD5(RAND()) FROM 1 FOR 5));

That should take care of it.

like image 44
ScottJShea Avatar answered Nov 08 '22 23:11

ScottJShea