SQL CURRENT_TIMESTAMP

The SQL CURRENT_TIMESTAMP function returns the current date and time of the database server. It is often used in database records to store timestamps for created or updated rows.

In this tutorial, we will explore the SQL CURRENT_TIMESTAMP function, its syntax, and practical examples demonstrating its usage.


Syntax of SQL CURRENT_TIMESTAMP

The basic syntax of the CURRENT_TIMESTAMP function is as follows:

</>
Copy
SELECT CURRENT_TIMESTAMP;

CURRENT_TIMESTAMP can also be used as a default value for a column in a table:

</>
Copy
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step-by-Step Examples Using SQL CURRENT_TIMESTAMP

1. Fetching the Current Timestamp

To retrieve the current timestamp of the database server, we can use the following query:

</>
Copy
SELECT CURRENT_TIMESTAMP AS log_timestamp;

Explanation:

  • This query returns the current date and time as per the database server’s timezone.
  • The result format is typically YYYY-MM-DD HH:MI:SS.

2. Using CURRENT_TIMESTAMP in an INSERT Statement

Let’s insert some user records into a table with automatic timestamp generation.

</>
Copy
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Insert sample records:

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

Retrieve the records:

</>
Copy
SELECT * FROM users;

Explanation:

  • The created_at column is automatically populated with the current timestamp when a new row is inserted.
  • Each record will have a different timestamp based on when the query is executed.

Conclusion

The CURRENT_TIMESTAMP function is used for tracking time-based data in SQL databases. In this tutorial, we covered:

  1. How to fetch the current timestamp using CURRENT_TIMESTAMP.
  2. How to use CURRENT_TIMESTAMP as a default value in a table.
  3. Examples demonstrating its use in inserting records and retrieving timestamps.