SQL SYSDATETIME

The SYSDATETIME function in SQL is used to return the current system date and time of the database server. It provides a high-precision datetime value, including fractional seconds up to seven decimal places.

In this tutorial, we will explore the SYSDATETIME function, its syntax, and practical usage with examples.


Syntax of SQL SYSDATETIME Function

The basic syntax of the SYSDATETIME function is as follows:

</>
Copy
SELECT SYSDATETIME() AS current_datetime;

Explanation:

  • SYSDATETIME(): Returns the current system date and time with high precision.
  • Can be used in SELECT queries, table inserts, and data manipulations.

Step-by-Step Examples Using SYSDATETIME

1. Fetching the Current Date and Time

To get the current system date and time, run the following query:

</>
Copy
SELECT SYSDATETIME() AS current_datetime;

Example Output:

Explanation:

  • The query retrieves the system’s current date and time with microsecond precision.
  • This function is useful for logging timestamps, auditing, and tracking system events.

2. Using SYSDATETIME in an Insert Statement

Let’s create a users table and insert records with the current timestamp:

</>
Copy
CREATE TABLE users (
    id INT PRIMARY KEY IDENTITY(1,1),
    name VARCHAR(50),
    registration_date DATETIME2
);

Now, insert some sample records using SYSDATETIME():

</>
Copy
INSERT INTO users (name, registration_date)
VALUES 
('Arjun', SYSDATETIME()),
('Ram', SYSDATETIME()),
('Priya', SYSDATETIME());

To verify the inserted records, use:

</>
Copy
SELECT * FROM users;

Example Output:

Explanation:

  • Each inserted record has the current timestamp recorded at the time of execution.
  • This is useful for tracking user sign-ups, logins, or any event-based transactions.

Conclusion

The SYSDATETIME function in SQL provides the current system date and time with high precision. In this tutorial, we covered:

  1. The syntax of SYSDATETIME().
  2. How to retrieve the current system date and time.
  3. Using SYSDATETIME() in an INSERT statement to track timestamps.