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.

Posted on

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

  1. 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.

  2. Select records based on current timestamp:

    SELECT * FROM orders
    WHERE order_date > CURRENT_TIMESTAMP();
    

    This returns future orders placed after the current timestamp.

  3. 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.

  4. 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.

  5. 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 time
  • SYSDATE() - Current date and time
  • UNIX_TIMESTAMP() - Unix timestamp

So CURRENT_TIMESTAMP() provides an easy way to use the current date and time as a timestamp in MySQL.