Skip to content

Instantly share code, notes, and snippets.

@vordan
Last active September 6, 2023 18:07
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vordan/ba944648300efcbc4cfc240a6b21af13 to your computer and use it in GitHub Desktop.
Save vordan/ba944648300efcbc4cfc240a6b21af13 to your computer and use it in GitHub Desktop.
Generate random date between two dates in MySQL
select
concat(round(rand() * 10000),
round(rand() * 10000),
round(rand() * 10000),
round(rand() * 10000)
) as rnd
;
select date_format(
from_unixtime(
rand() *
(unix_timestamp('1967-11-13 16:00:00') - unix_timestamp('1990-11-13 23:00:00')) +
unix_timestamp('1990-11-13 23:00:00')
), '%Y-%m-%d %H:%i:%s') as datum_roden
;
select
concat(
'0', floor(rand() * (79 - 70 + 1)) + 70, '/',
floor(rand() * 401) + 100, '-',
floor(rand() * 401) + 100
)
;
Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min>
generates a number between <min> and <max> inclusive.
-- Between 17 and 44
select floor(rand() * (44 - 17 + 1)) + 17;
@ZsoltDM
Copy link

ZsoltDM commented Sep 6, 2023

/*
   Range: 
       - from (min. value):   unix_timestamp('2023-01-01 01:00:00')
       - to   (max. value):   unix_timestamp(CURRENT_TIMESTAMP())
   Technical random value :   (rand() * ((unix_timestamp(CURRENT_TIMESTAMP())) - unix_timestamp('2023-01-01 01:00:00'))) (approximately :-) )
 */
select date_format(
                   from_unixtime(
					             unix_timestamp('2023-01-01 01:00:00') 
					             + 
                                                     -- Max random value test
					             -- (1 * ((unix_timestamp(CURRENT_TIMESTAMP())) - unix_timestamp('2023-01-01 01:00:00'))) 
                                 (rand() * ((unix_timestamp(CURRENT_TIMESTAMP())) - unix_timestamp('2023-01-01 01:00:00')))
					            ),
				   '%Y-%m-%d %H:%i:%s') as datum_roden	            
;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment