Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate a MySQL table with many random numbers?

Tags:

mysql

I'm going to ask a question that has been asked in very abstract terms, with (understandably) no concrete answers provided:

From the MySQL prompt, how do I create and populate a table, rand_numbers, with one column, number INT, and 1111 rows, where the number column holds a random number between 2222 and 5555?

Something like:

CREATE TABLE rand_numbers(number INT);   #run following line 1111 times INSERT INTO rand_numbers (number) VALUES (2222 + CEIL( RAND() * 3333)); 

This question has been asked, but either relies on external languages for the loop or is far too general. I would like to know if it's possible to do something this simple from a typical Linux MySQL prompt.

like image 239
drug_user841417 Avatar asked Jun 14 '12 23:06

drug_user841417


People also ask

How do I fill a column with random numbers in MySQL?

UPDATE yourTableName set yourColumnName=value where yourColumnName2=(SELECT FLOOR(1+RAND()*3)); In the above query, the statement FLOOR(1+RAND()*3) generates the number between 1-3 and update the column.

How do you populate a table in MySQL?

In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

How do you insert a random value in a table?

To create a random integer number between two values (range), you can use the following formula: SELECT 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.


1 Answers

To create the table use:

CREATE TABLE rand_numbers (     number INT NOT NULL ) ENGINE = MYISAM; 

Then to populate it with random values, you can define a stored procedure (which supports looping):

DELIMITER $$ CREATE PROCEDURE InsertRand(IN NumRows INT, IN MinVal INT, IN MaxVal INT)     BEGIN         DECLARE i INT;         SET i = 1;         START TRANSACTION;         WHILE i <= NumRows DO             INSERT INTO rand_numbers VALUES (MinVal + CEIL(RAND() * (MaxVal - MinVal)));             SET i = i + 1;         END WHILE;         COMMIT;     END$$ DELIMITER ;  CALL InsertRand(1111, 2222, 5555); 

Then you can reuse that procedure to insert more random values based on different parameters.. say 600 rows with random values between 1200 and 8500:

CALL InsertRand(600, 1200, 8500); 
like image 60
Zane Bien Avatar answered Oct 11 '22 10:10

Zane Bien