GETDATE()

Description

Returns the current database system timestamp as a datetime value.

GETDATE() is a nondeterministic function. Every time GETDATE() is referenced in a statement, it returns a different value. (This applies to the time of execution, not the date).

Syntax

GETDATE ( )

Return Value

Returns the current system date and time as a datetime value.

Remarks

GETDATE() returns the value from the operating system. The datetime value returned by GETDATE() can be used to compare with other datetime values, or to set default values for columns.

GETDATE() is equivalent to SYSDATETIME() with a lower precision. In newer versions of SQL Server, it is recommended to use SYSDATETIME() or GETUTCDATE() for better precision and accuracy.

Note: The datetime data type has a range from January 1, 1753, through June 3, 1999, of the Gregorian calendar.

Examples

A. Get the current date and time.

SELECT GETDATE();

This query returns the current date and time from the SQL Server system. The output will vary based on when the query is executed.

B. Use GETDATE() in a WHERE clause.

SELECT *
FROM Orders
WHERE OrderDate < GETDATE() - 7;

This example retrieves orders placed more than 7 days ago by comparing the OrderDate with the current date minus 7 days.

C. Use GETDATE() as a default constraint.

CREATE TABLE AuditLog (
    LogID INT PRIMARY KEY IDENTITY(1,1),
    ActionDescription NVARCHAR(255),
    LogTimestamp DATETIME DEFAULT GETDATE()
);

INSERT INTO AuditLog (ActionDescription) VALUES ('User logged in.');
SELECT * FROM AuditLog;

This demonstrates how to set GETDATE() as the default value for the LogTimestamp column in the AuditLog table.