I have a column called date_created and I want each row to hold a random date with a date margin of -2 days from the current time.
I am running the below query but it updates all the rows with the same random date. I want every row to be random and not the same.
update table set date_created=(select NOW() + (random() * (NOW()+'-2 days' - NOW())) + '-2 days')
Any idea would be appreciated.
Use an expression in place of a query:
update my_table
set date_created= NOW() + (random() * (NOW()+'-2 days' - NOW())) + '-2 days'
PostgreSQL is optimizing your subquery so that it's only run once, causing the same random value to be used for all rows. To ensure random() is run once for each row, use an expression instead of a subquery. Also, your calculation can be simplified a bit.
Suggested improved query:
UPDATE my_table SET date_created = now() - random() * INTERVAL '2 days'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With