How to Use now() Function in MySQL: Syntax and Examples
In MySQL, use the
now() function to get the current date and time in the format 'YYYY-MM-DD HH:MM:SS'. It is commonly used in queries to insert or compare timestamps representing the current moment.Syntax
The now() function has no parameters and returns the current date and time as a DATETIME value.
now(): Returns the current date and time.
sql
SELECT now();
Output
2024-06-15 14:30:45
Example
This example shows how to use now() to insert the current timestamp into a table and then select it.
sql
CREATE TABLE events ( id INT AUTO_INCREMENT PRIMARY KEY, event_name VARCHAR(50), event_time DATETIME ); INSERT INTO events (event_name, event_time) VALUES ('Meeting', now()); SELECT * FROM events;
Output
1 | Meeting | 2024-06-15 14:30:45
Common Pitfalls
Some common mistakes when using now() include:
- Using
now()in a query expecting a date only, which returns date and time. - Confusing
now()withcurdate()which returns only the date. - Expecting
now()to update automatically after insertion; it captures the time at query execution.
sql
/* Wrong: expecting only date */ SELECT now() = curdate(); /* Right: use curdate() for date only */ SELECT curdate();
Output
0
2024-06-15
Quick Reference
| Function | Description | Returns |
|---|---|---|
| now() | Current date and time | DATETIME (YYYY-MM-DD HH:MM:SS) |
| curdate() | Current date only | DATE (YYYY-MM-DD) |
| current_timestamp() | Synonym for now() | DATETIME (YYYY-MM-DD HH:MM:SS) |
Key Takeaways
Use
now() to get the current date and time in MySQL.now() returns a DATETIME value including both date and time.For date only, use
curdate() instead of now().now() captures the time when the query runs, not dynamically updated later.Use
now() in INSERT or WHERE clauses to work with current timestamps.