Insert/ Update random date in MySQL

MysqlSqlDateRandom

Mysql Problem Overview


How would I update a column with a random date in the past 2 weeks using MySQL?

For example (code doesn't actually work):

UPDATE mytable
SET col = sysdate() - rand(1, 14);

Mysql Solutions


Solution 1 - Mysql

You can get a random integer with this expression:

> To obtain a random integer R in the > range i <= R < j, use the expression > FLOOR(i + RAND() * (j - i)). For > example, to obtain a random integer in > the range the range 7 <= R < 12, you > could use the following statement: > > SELECT FLOOR(7 + (RAND() * 5));

https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_rand

Use that to generate a random number of days, hours or minutes (depending on the resolution) and add that number to current date.

Full expression would be:

-- Date only
SELECT CURRENT_DATE - INTERVAL FLOOR(RAND() * 14) DAY;

-- Date and time SELECT CURRENT_TIMESTAMP - INTERVAL FLOOR(RAND() * 14 * 24 * 60 *60) SECOND;

Demo

Solution 2 - Mysql

UPDATE mytable
SET col = CURRENT_DATE - INTERVAL FLOOR(RAND() * 14) DAY

This sets col to a date between (and including) current date and current date - 13 days. Multiply by 15 to get current date - 14 days.

Solution 3 - Mysql

Your main problem is that RAND() doesn't allow a range of values like you specify. It will always return a value between 0 and 1.

I can't work out a 1..14 random solution right now, but to get you started, this will pick a random date within the last 10 days:

SET col = DATE(DATE_SUB(NOW(), INTERVAL ROUND(RAND(1)*10) DAY)) 

Solution 4 - Mysql

One simple option is to use this query:

UPDATE mytable
SET col = (
    NOW() - INTERVAL FLOOR(RAND() * 14) DAY 
    + INTERVAL FLOOR(RAND() * 23) HOUR
    + INTERVAL FLOOR(RAND() * 59) MINUTE
    + INTERVAL FLOOR(RAND() * 59) SECOND
);

Or, more elegant:

UPDATE mytable
SET col = (NOW() - INTERVAL FLOOR(RAND() * 14 * 24 * 60 * 60) SECOND);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlairView Question on Stackoverflow
Solution 1 - MysqlÁlvaro GonzálezView Answer on Stackoverflow
Solution 2 - MysqlSalman AView Answer on Stackoverflow
Solution 3 - MysqlPekkaView Answer on Stackoverflow
Solution 4 - MysqlguyaloniView Answer on Stackoverflow