Open In App

SQL Server GETDATE() Function

Last Updated : 15 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

SQL Server GETDATE() function returns the current date and time of the database system in a ‘YYYY-MM-DD hh:mm:ss.mmm’ format.

Note:

GETDATE() is similar to other date and time functions like CURRENT_TIMESTAMP, SYSDATETIME(), and GETUTCDATE(), but differs primarily in terms of the time zone and precision of the returned values.

While GETDATE() returns the current date and time in the local time zone with lower precision, CURRENT_TIMESTAMP and GETUTCDATE() return the current date and time in the UTC time zone, and SYSDATETIME() returns the current date and time in the local time zone but with higher precision compared to GETDATE().

Syntax

The GETDATE() function syntax is:

GETDATE()

SQL Server GETDATE() Function Examples

Let’s look at some examples of the GETDATE() function in SQL Server.

Query:

SELECT GETDATE();

Output :

2021-01-03 14:42:58.970

Here, the output will vary each time the code is compiled, as this method returns the current date and time.

Using GETDATE() as a DEFAULT value

In SQL Server, GETDATE() can be used as a default value for a column to automatically set the current date and time when a new row is inserted. This is particularly useful for tracking the date and time of creation or modification of a record.

Query:

CREATE TABLE get_date
(
  id_num INT IDENTITY,
  message VARCHAR(150) NOT NULL,
  generated_at DATETIME NOT NULL DEFAULT GETDATE(),
  PRIMARY KEY(id_num)
);

Inserting Data :

INSERT INTO get_date(message)
VALUES('Its the first message.');

INSERT INTO get_date(message)
VALUES('get_date');

Read Data :

SELECT id_num, message, generated_at
FROM get_date;

Output :

Index No. id_num message generated_at
1 1 Its the first message.  03.01.2021 15:49:48
2 2 get_date 03.01.2021 15:49:48

As you can see, it shows the time of creation of these columns.



Next Article
Article Tags :

Similar Reads