Home > Database > Mysql Tutorial > How to Correctly Add Time to the Current Timestamp in MySQL?

How to Correctly Add Time to the Current Timestamp in MySQL?

Linda Hamilton
Release: 2024-12-10 21:14:12
Original
947 people have browsed it

How to Correctly Add Time to the Current Timestamp in MySQL?

How to Add Time to Current Timestamp in MySQL?

When working with temporal data in MySQL, it's often necessary to perform calculations involving time manipulation. One such operation is adding a specific duration to the current timestamp.

Consider the example of fetching courses from a courses table where the start time is greater than the current time plus 2 hours. The following query attempts to achieve this:

SELECT * FROM courses WHERE (now() + 2 hours) > start_time;
Copy after login

However, this query syntax is incorrect. To correctly add 2 hours to the current timestamp in MySQL, use the DATE_ADD() function:

SELECT * 
FROM courses 
WHERE DATE_ADD(NOW(), INTERVAL 2 HOUR) > start_time;
Copy after login

The DATE_ADD() function takes the current timestamp (NOW()), adds an interval of 2 hours (INTERVAL 2 HOUR), and compares the result with the start_time field of the courses table.

By using the correct syntax, you can effectively retrieve courses that start more than 2 hours from now.

The above is the detailed content of How to Correctly Add Time to the Current Timestamp in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template