SQL Server GETDATE() Function

In SQL Server, the GETDATE() function is used to return the current system date and time. It can be used to obtain the current timestamp in SQL queries or as a default value for timestamp columns in a table.

Syntax

GETDATE()

Usage

The GETDATE() function is commonly used in the following scenarios:

  • To obtain the current date and timestamp
  • To set the default value for timestamp columns in a table

Examples

Example 1

Assuming there is a table named orders with a timestamp column named order_time. To set the order_time column to the current timestamp when inserting new rows into the table, use the following SQL query:

INSERT INTO orders (order_id, order_time, customer_id)
VALUES (12345, GETDATE(), 789);

After executing the query, the order_time column will contain the current date and timestamp.

Example 2

Assuming you want to add a column named timestamp to the query result that contains the current timestamp. Use the following SQL query:

SELECT order_id, customer_id, order_total, GETDATE() AS timestamp
FROM orders;

After executing the query, the result set will contain a timestamp column with the current timestamp.

Conclusion

The GETDATE() function is used in SQL Server to obtain the current system date and timestamp, and is commonly used to set the default value for timestamp columns in a table or to add a current timestamp column to a query result.