SQL GETDATE Function

The SQL GETDATE() function is used to retrieve the current date and time based on the system’s clock. It is commonly used in SQL queries to store timestamps, filter records based on date, and perform date-based calculations.

In this tutorial, we will explore the GETDATE() function in SQL, understand its syntax, and see practical examples.


Syntax of SQL GETDATE Function

The syntax for the GETDATE() function is straightforward:

</>
Copy
SELECT GETDATE();

Explanation:

  • The GETDATE() function returns the current date and time of the database server.
  • The output format is typically YYYY-MM-DD HH:MI:SS.MMM.
  • This function is widely used in scenarios where the system date and time are required for logging, filtering, or tracking changes.

Step-by-Step Examples Using SQL GETDATE()

1. Retrieving the Current Date and Time

To fetch the current system date and time:

</>
Copy
SELECT GETDATE() AS current_datetime;

Output Example:

Explanation:

  • The query retrieves the current date and time.
  • The result is formatted in YYYY-MM-DD HH:MI:SS.MMM format.

2. Using GETDATE() in a Table

Let’s create a table employees where we store employee details along with their joining date, using GETDATE() to capture the current timestamp.

</>
Copy
CREATE TABLE employees (
    id INT PRIMARY KEY IDENTITY(1,1),
    name VARCHAR(50),
    department VARCHAR(50),
    joining_date DATETIME DEFAULT GETDATE()
);

Now, let’s insert some employees into the table:

</>
Copy
INSERT INTO employees (name, department) 
VALUES 
('Arjun', 'IT'),
('Ram', 'Finance'),
('Priya', 'HR');

To verify the records:

</>
Copy
SELECT * FROM employees;

Output Example:

Explanation:

  • The joining_date column automatically stores the current date and time when a new employee is inserted.
  • GETDATE() ensures that each new record has a timestamp reflecting when it was created.

Conclusion

The GETDATE() function is used for handling date and time operations in SQL. In this tutorial, we covered:

  1. How to use GETDATE() to retrieve the current system date and time.
  2. How to apply GETDATE() in a table to store timestamps.
  3. Practical examples showing real-world applications.