How to use the MySQL CURRENT_TIMESTAMP() function
The CURRENT_TIMESTAMP() function in MySQL returns the current date and time as a timestamp value. It is useful for inserting records with the current timestamp.
The CURRENT_TIMESTAMP() function in MySQL returns the current date and time as a timestamp value. It is useful for inserting records with the current timestamp.
Syntax
The syntax for CURRENT_TIMESTAMP() is:
CURRENT_TIMESTAMP
CURRENT_TIMESTAMP([fsp])
Where the optional fsp argument specifies the fractional seconds precision for the return value.
Examples
-
Insert current timestamp into a table:
INSERT INTO logs (entry_time) VALUES (CURRENT_TIMESTAMP());This will insert the current date and time as the entry_time for the log.
-
Select records based on current timestamp:
SELECT * FROM orders WHERE order_date > CURRENT_TIMESTAMP();This returns future orders placed after the current timestamp.
-
Update a timestamp column to current timestamp:
UPDATE users SET last_login = CURRENT_TIMESTAMP() WHERE id = 1;This updates the last_login field to the current timestamp for the user.
-
Default a timestamp column to current timestamp:
CREATE TABLE comments ( id INT AUTO_INCREMENT, text VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP() );This will auto-populate created_at with the current timestamp.
-
Get the current timestamp as a string:
SELECT CAST(CURRENT_TIMESTAMP() AS CHAR);This converts the current timestamp to a string representation.
Other Similar Functions
NOW()- Current date and timeSYSDATE()- Current date and timeUNIX_TIMESTAMP()- Unix timestamp
So CURRENT_TIMESTAMP() provides an easy way to use the current date and time as a timestamp in MySQL.