Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql insert random datetime in a given datetime range

Tags:

sql

mysql

With SQL , Can I insert random datetime values in a column giving a range?

For example, given a range of 2010-04-30 14:53:27 to 2012-04-30 14:53:27

I'm getting confused with the range part. as i will have just done this

INSERT INTO `sometable` VALUES (RND (DATETIME()))  
like image 683
karto Avatar asked Aug 10 '12 17:08

karto


People also ask

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 insert a date in MySQL?

The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD.

How do I query a date in MySQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)


2 Answers

Here is an example that should help:

INSERT INTO `sometable` VALUES(     FROM_UNIXTIME(         UNIX_TIMESTAMP('2010-04-30 14:53:27') + FLOOR(0 + (RAND() * 63072000))     ) ) 

It uses the date 2010-04-30 14:53:27 as the base, converts that to a Unix timestamp, and adds a random number of seconds from 0 to +2 years to the base date and converts it back to a DATETIME.

It should be pretty close but over longer time periods leap years and other adjustments will throw it off.

like image 170
drew010 Avatar answered Sep 26 '22 16:09

drew010


This should work nicely:

SET @MIN = '2010-04-30 14:53:27'; SET @MAX = '2012-04-30 14:53:27'; SELECT TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN); 

TIMESTAMPDIFF is used to determine the number of seconds in the date range. Multiply this by a random number between 0-1 results in a random number between 0 and the number of seconds in the range. Adding this random number of seconds to the lower bound of the range results in a random date between the data range bounds.

like image 22
Brent Worden Avatar answered Sep 25 '22 16:09

Brent Worden