MySQL NOW() Function
The NOW()
function in MySQL is used to retrieve the current date and time in the format YYYY-MM-DD HH:MM:SS
. It is a simple and essential function for working with timestamps, often used for recording the current moment when an event occurs, such as inserting or updating records.
Syntax
- The
NOW()
function does not take any arguments.
Output Format
Default Format: The result is returned as a
DATETIME
value.Example Output:
Examples
1. Basic Usage
To get the current date and time:
Output:
2. Using NOW() in Insert Statements
You can use NOW()
to automatically record the current timestamp when adding a new record:
Here, order_date
will be set to the current date and time.
3. Comparing with a Timestamp
Retrieve records where the timestamp is within the last 7 days:
4. Extracting Components from NOW()
You can use functions like DATE()
, YEAR()
, MONTH()
, and DAY()
to extract specific components from NOW()
:
Get the current date (without time):
Get the current year:
Get the current month:
Get the current time:
5. Using NOW() in Update Statements
Update a record’s last modified date:
Practical Applications
Tracking Creation or Modification Times: Use
NOW()
to populatecreated_at
andupdated_at
fields in tables for logging purposes.Scheduling Tasks: Calculate future or past dates relative to
NOW()
:Filtering Data: Retrieve data created or modified within a specific timeframe:
Comparison with Other Time Functions
Function | Description | Example Output |
---|---|---|
CURDATE() | Returns the current date without time. | 2025-01-12 |
CURTIME() | Returns the current time without date. | 14:30:45 |
SYSDATE() | Returns the date and time at the moment it is executed. | 2025-01-12 14:30:45 |
UTC_TIMESTAMP() | Returns the current UTC date and time. | 2025-01-12 19:30:45 |
Key Points to Remember
NOW()
always returns the current date and time based on the server's timezone settings.- If you need a UTC equivalent, use
UTC_TIMESTAMP()
. - To ensure consistency in applications, set the server's timezone using the
default-time-zone
option in MySQL configuration.
Conclusion
The NOW()
function is an indispensable tool for managing date and time in MySQL. Its simplicity and versatility make it ideal for real-time data tracking, timestamping, and scheduling tasks. By understanding its usage and integration with other date and time functions, you can effectively handle time-sensitive operations in your database.