Skip to content

GETDATE Date and Time Function

The GETDATE date function returns the current system date and time in the SQL Server standard internal format for DATETIME values. The syntax of the GETDATE date function is as follows:

GETDATE()

The GETDATE date function is a non-deterministic function and view and expressions that reference this column cannot be indexed.

Sample Uses of the GETDATE Date and Time Function

Here are a few uses of the GETDATE date function:

Usage #1 : Log the Date and Time When a Row is Inserted in a Table

CREATE TABLE [dbo].[Users] ( 
    [UserName]          VARCHAR(10),
    [FirstName]         VARCHAR(50),
    [LastName]          VARCHAR(50),
    [CreationDate]      DATETIME DEFAULT ( GETDATE() )
)

INSERT INTO [dbo].[Users] ( [UserName], [FirstName], [LastName] )
VALUES ( 'sysadmin', 'System', 'Administrator' )

Usage #2 : Generate a Random Number

SELECT DATEPART(MS, GETDATE()) AS [Random Number]

Usage #3 : Generate a Random Number Within a Range

DECLARE @MinValue     INT
DECLARE @MaxValue     INT

SET @MinValue = 51
SET @MaxValue = 100

SELECT (DATEPART(MS, GETDATE()) % ( @MaxValue - @MinValue + 1)) + @MinValue AS [Random Number]

Usage #4 : Generate an Account Number, Reference Number or Tracking Number

-- Assuming [dbo].[Tracking] Table Contains All Existing Tracking Numbers
DECLARE @NewNumber        DECIMAL(10, 0)

SELECT @NewNumber = MAX([TrackingNumber]) + 1
FROM [dbo].[Tracking]
WHERE [TrackingNumber] > YEAR(GETDATE()) * 1000000 + MONTH(GETDATE()) * 10000 + DAY(GETDATE()) * 100

IF @NewNumber IS NULL
    SET @NewNumber = YEAR(GETDATE()) * 1000000 + MONTH(GETDATE()) * 10000 + DAY(GETDATE()) * 100 + 1

Usage #5 : Return a Random Number of Records

SELECT TOP (DATEPART(MS, GETDATE())) *
FROM [master].[dbo].[spt_values]
ORDER BY NEWID()