Daily Shaarli

All links of one day in a single page.
Random Date Generator in SQL Server
thumbnail

In this article we look at how to generate random dates in SQL Server to build a sample dataset along with code and examples.

SELECT DATEADD(DAY, RAND(CHECKSUM(NEWID()))*(1+DATEDIFF(DAY, @StartDate, @EndDate)),@StartDate) AS 'SalesDate';

CHECKSUM(NEWID()) is the salt for the rand() function

NEWID() generates a random unique ID for a row. Ordering by NEWID() will randomly order query results. Adding a TOP statement will return a finite number of random rows. For example, to get 10 random rows from a table:

SELECT TOP 10 * 
FROM tablename 
WHERE condition
ORDER BY NEWID()