Blair
Blair

Reputation: 3751

Insert/ Update random date in MySQL

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);

Upvotes: 57

Views: 46307

Answers (4)

Salman Arshad
Salman Arshad

Reputation: 272006

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

This sets col to a date between current date - 13 days and current date; both inclusive, total 14 days.

Upvotes: 32

Álvaro González
Álvaro González

Reputation: 146370

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

Upvotes: 96

guyaloni
guyaloni

Reputation: 5862

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);

Upvotes: 8

Pekka
Pekka

Reputation: 449385

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)) 

Upvotes: 10

Related Questions