How can hours be added to a datetime in MySQL?

How to Add Hours to a Datetime in MySQL

Managing and manipulating temporal data is a core requirement in relational database systems. When working with DATETIME fields in MySQL, developers frequently encounter scenarios where they need to advance a timestamp by a specified amount of time, such as adding a certain number of hours. The standard and most robust method for achieving this time adjustment is by utilizing the built-in DATE_ADD function.

The DATE_ADD function is designed specifically for performing date arithmetic. It requires three fundamental arguments: the initial date or datetime value, the numerical interval of time to be added, and the corresponding unit of time (e.g., minutes, days, or hours). This powerful combination ensures precise manipulation of temporal records. While DATE_ADD is the preferred method for complex operations, ADDTIME offers a simpler, specialized alternative for adding fixed time values (formatted as ‘HH:MM:SS’) to existing timestamps. Mastering both functions is essential for effective SQL development.


You can use the DATE_ADD() function in MySQL to add a specific number of hours to a datetime field in MySQL.

For example, you can use the following syntax to create a new column that adds 3 hours to the existing datetime in the sales_time column of a table named sales. This method allows for immediate calculation without altering the underlying data.

SELECT sales_time, DATE_ADD(sales_time, INTERVAL 3 HOUR)
FROM sales;

The following detailed sections will demonstrate how to implement this syntax in a practical scenario, including table creation, data insertion, and viewing the results of the modified time calculation.

Understanding Date and Time Manipulation in MySQL

In data management, the ability to accurately manipulate timestamps is critical for tasks ranging from scheduling future events to calculating service level agreements (SLAs). MySQL provides a rich suite of functions tailored for temporal arithmetic. The primary functions like DATE_ADD are designed to handle complexities such as crossing date boundaries, daylight savings transitions (though not automatically handled by MySQL itself, the calculation is accurate), and ensuring correct time zone representations based on server configuration.

When we seek to increment a timestamp by hours, we are performing a precise mathematical operation on a date and time object. The core challenge lies in telling the database not just how much time to add, but what unit that time represents. This is where the INTERVAL keyword becomes indispensable, defining the scope and magnitude of the change. Using DATE_ADD with the HOUR unit is the most efficient and readable way to execute this specific requirement, adhering to standard SQL conventions.

Furthermore, it is important to differentiate this process from simple string concatenation. Since DATETIME values are stored internally as structured data points, using dedicated functions ensures that the resulting calculation is calendar-aware. For instance, adding three hours to 23:00:00 correctly increments the date component, resulting in a time on the following day (02:00:00). Attempting to perform this calculation manually or via less appropriate functions would risk errors, especially when dealing with large datasets or complex reporting requirements.

The Primary Method: Utilizing the DATE_ADD Function

The DATE_ADD function is the cornerstone of date arithmetic in MySQL. Its versatility allows developers to add any specified time unit—from microseconds up to years—to an existing date or datetime field. The formal structure of the function requires clarity regarding the source data and the intended modification. By specifying the unit as HOUR, we direct the function to calculate the new timestamp precisely three hours forward from the original value.

The flexibility of DATE_ADD extends beyond fixed values. The interval argument can be derived dynamically from other columns or variables within a query. For instance, if a table included a column specifying a required processing time in hours, that column’s value could be plugged directly into the interval parameter. This dynamic capability is particularly useful in business logic where processing times or delivery windows vary by record, ensuring maximum efficiency and minimal need for application-level calculations.

It is worth noting that DATE_ADD is functionally synonymous with the ADDDATE function when using the INTERVAL keyword, though DATE_ADD is generally preferred for consistency and explicit definition of the time unit. By understanding and routinely employing this primary function, developers maintain high standards of code readability and data integrity across their database operations.

Syntax Breakdown of DATE_ADD for Hour Calculation

To ensure successful execution, the syntax for DATE_ADD must follow a strict pattern. The command is structured as DATE_ADD(date, INTERVAL value unit). The first parameter, date, is the column or literal datetime value you wish to modify. The second parameter is the compound expression consisting of the INTERVAL keyword, the numerical value (e.g., 3), and the specific unit (e.g., HOUR). When selecting data using this function, we often display both the original timestamp and the calculated timestamp for comparison.

In the context of adding hours, the unit must be specified as HOUR. If you needed to add different units simultaneously, MySQL supports composite intervals like INTERVAL '3:30' HOUR_MINUTE, which would add three hours and thirty minutes. However, for the simple addition of discrete hours, INTERVAL 3 HOUR is the clearest and most direct approach. This explicit definition minimizes ambiguity and ensures that the database engine performs the calculation as intended, without relying on implicit type conversions.

For example, to calculate a new time that is 3 hours later than the existing sales_time in a table named sales, the full query utilizes the SELECT statement to retrieve the original value alongside the new calculated value. This standard practice allows for validation and reporting: SELECT sales_time, DATE_ADD(sales_time, INTERVAL 3 HOUR) FROM sales; The resulting dataset will contain two columns: the unadjusted original time and the new time, offset by the specified interval.

Alternative Approach: Employing the ADDTIME Function

While DATE_ADD is the versatile choice for all date/time manipulation, the ADDTIME() function provides a straightforward alternative specifically tailored for adding a time component (hours, minutes, and seconds) to either a DATETIME or TIME value. Unlike DATE_ADD, which uses the INTERVAL syntax, ADDTIME takes two string or time arguments: the starting time/datetime, and the time value to be added, typically formatted as a string like 'HH:MM:SS'.

If the requirement is simply to add a fixed duration of hours, minutes, and seconds, ADDTIME offers cleaner syntax without the need for the INTERVAL keyword. For instance, adding three hours using ADDTIME would look like this: ADDTIME(sales_time, '03:00:00'). This function is particularly useful when dealing with strict time durations where the focus is purely on the elapsed time rather than complex calendar units like months or quarters.

However, developers should be aware of ADDTIME‘s limitations compared to DATE_ADD. ADDTIME is less flexible when dealing with non-standard units (like weeks or quarters) and is generally reserved for operations involving hours, minutes, and seconds. For most production environments involving dynamic intervals or complex reporting, DATE_ADD remains the industry standard. Nonetheless, ADDTIME serves as an excellent, simple tool for fixed hour addition when portability across different database systems is not a primary concern.

Setting Up the Practical Example Table

To illustrate the functionality of DATE_ADD practically, we will create a sample table named sales. This table simulates a real-world scenario where a retail company tracks transactions, requiring us to manage and analyze the exact time of sale. The table structure will include a unique identifier, an item description, and the crucial sales_time column, which utilizes the DATETIME data type to store both the date and time of the transaction.

The careful selection of the DATETIME data type ensures that the time component is accurately preserved alongside the date, making it suitable for granular time arithmetic. We will then populate this table with five representative rows, each recording a different item sold at a unique time. This diverse dataset is essential for demonstrating how DATE_ADD correctly handles various scenarios, including transactions that occur late in the day, potentially crossing over into the next calendar date.

The following SQL script provides the commands necessary to set up this environment. Note the use of PRIMARY KEY and NOT NULL constraints to maintain data integrity, which are best practices in any relational database design. The subsequent output confirms the successful creation and population of the table, ready for our temporal calculation exercise.

-- create table 
CREATE TABLE sales (
  store_ID INT PRIMARY KEY,
  item TEXT NOT NULL,
  sales_time DATETIME NOT NULL
);

-- insert rows into table
INSERT INTO sales VALUES (0001, 'Oranges', '2024-02-10 03:45:00');
INSERT INTO sales VALUES (0002, 'Apples', '2020-11-25 15:25:01');
INSERT INTO sales VALUES (0003, 'Bananas', '2009-06-30 09:01:39');
INSERT INTO sales VALUES (0004, 'Melons', '2024-01-14 03:29:55');
INSERT INTO sales VALUES (0005, 'Grapes', '2023-05-19 23:10:04');

-- view all rows in table
SELECT * FROM sales;

Output of Sales Table:

+----------+---------+---------------------+
| store_ID | item    | sales_time          |
+----------+---------+---------------------+
|        1 | Oranges | 2024-02-10 03:45:00 |
|        2 | Apples  | 2020-11-25 15:25:01 |
|        3 | Bananas | 2009-06-30 09:01:39 |
|        4 | Melons  | 2024-01-14 03:29:55 |
|        5 | Grapes  | 2023-05-19 23:10:04 |
+----------+---------+---------------------+

With the sample data established, our next step is to apply the DATE_ADD function to the sales_time column, calculating a future timestamp that is exactly three hours later for every recorded transaction.

Executing the DATE_ADD Query

Our primary objective is to select the existing timestamps from the sales_time column and generate a new, temporary column that reflects the original time plus an additional three hours. This type of calculation is commonly required for simulating delivery deadlines, scheduling follow-up communications, or adjusting logs for time zone differences before aggregation.

We execute the following query, leveraging the DATE_ADD function with the INTERVAL 3 HOUR clause. This specifically instructs MySQL to interpret the numerical value ‘3’ as the quantity of hours to be added to the base DATETIME value found in sales_time. The query structure is clean and focuses purely on the selection and transformation of the data.

SELECT sales_time, DATE_ADD(sales_time, INTERVAL 3 HOUR)
FROM sales;

Output of Time Calculation:

+---------------------+---------------------------------------+
| sales_time          | DATE_ADD(sales_time, INTERVAL 3 HOUR) |
+---------------------+---------------------------------------+
| 2024-02-10 03:45:00 | 2024-02-10 06:45:00                   |
| 2020-11-25 15:25:01 | 2020-11-25 18:25:01                   |
| 2009-06-30 09:01:39 | 2009-06-30 12:01:39                   |
| 2024-01-14 03:29:55 | 2024-01-14 06:29:55                   |
| 2023-05-19 23:10:04 | 2023-05-20 02:10:04                   |
+---------------------+---------------------------------------+

A careful examination of the output reveals the effectiveness of the function, especially in the final row (Grapes), where the original time was 23:10:04 on May 19th. Adding three hours correctly resulted in 02:10:04 on May 20th. This validation confirms that DATE_ADD inherently manages date rollovers, preserving data accuracy across time boundaries.

Enhancing Readability with Aliases (Using AS)

While the calculated output provides the correct results, the default column name generated by MySQLDATE_ADD(sales_time, INTERVAL 3 HOUR)—is long and cumbersome for reports or application integration. To make the output significantly more user-friendly and readable, we utilize the AS keyword to assign an alias to the calculated column.

The use of aliases is a fundamental practice in professional SQL development, improving the clarity of the resulting dataset. By giving the new column a descriptive name, such as threehours_later or estimated_delivery, we immediately communicate the column’s purpose to any consumer of the data. This simplification is vital when integrating SQL results into external tools like BI dashboards or front-end applications.

We modify the previous query to include the AS clause, renaming the calculated column to threehours for concise referencing. This change affects only the output presentation; the underlying calculation logic remains identical. The revised query syntax and its resulting output demonstrate this improvement in dataset aesthetics and utility.

SELECT sales_time, DATE_ADD(sales_time, INTERVAL 3 HOUR) AS threehours
FROM sales;

+---------------------+---------------------+
| sales_time          | threehours          |
+---------------------+---------------------+
| 2024-02-10 03:45:00 | 2024-02-10 06:45:00 |
| 2020-11-25 15:25:01 | 2020-11-25 18:25:01 |
| 2009-06-30 09:01:39 | 2009-06-30 12:01:39 |
| 2024-01-14 03:29:55 | 2024-01-14 06:29:55 |
| 2023-05-19 23:10:04 | 2023-05-20 02:10:04 |
+---------------------+---------------------+

The resulting table is now highly optimized for reporting, clearly showing the original timestamp and the calculated timestamp under the distinct and easy-to-read column name threehours.

Handling Subtractions: The DATE_SUB Function

While the focus of this tutorial is addition, it is essential to mention the complementary function for moving timestamps backward in time. If a requirement dictates subtracting a specific number of hours, the DATE_SUB() function should be used instead of DATE_ADD. This function mirrors the syntax of DATE_ADD entirely but performs the inverse operation.

For example, to determine what the time was five hours prior to the transaction recorded in sales_time, the syntax would be: DATE_SUB(sales_time, INTERVAL 5 HOUR). Using DATE_SUB for subtraction is generally cleaner and more explicit than using DATE_ADD with a negative interval, though both methods yield the same mathematical result. The functional parity ensures developers can easily switch between forward and backward time calculations using standardized structures.

The consistent use of DATE_ADD for positive intervals and DATE_SUB for negative intervals simplifies debugging and maintenance. Both functions accept the same wide array of time units, ensuring that complex date arithmetic—whether moving forward or backward—can be handled efficiently within the MySQL environment.

Summary of Best Practices for Time Arithmetic

When performing time arithmetic in MySQL, employing best practices ensures accuracy, performance, and maintainability. Always prioritize the DATE_ADD (or DATE_SUB) function when dealing with units of time larger than seconds, especially hours, days, or months, as these functions are optimized for date rollover handling.

Always use the explicit INTERVAL keyword, followed by the numerical value and the unit (e.g., HOUR, DAY, MINUTE). Avoid relying on implicit arithmetic or less specific functions unless the requirement is strictly limited to time components (in which case ADDTIME may be considered). Furthermore, never forget to use the AS keyword when presenting calculated results to end-users or application layers, ensuring that the column names are clear, concise, and reflective of the data they contain.

By following these guidelines and mastering the use of the DATE_ADD function, developers can confidently manipulate DATETIME fields, addressing complex scheduling and logging requirements directly within their MySQL queries.

The following tutorials explain how to perform other common tasks in MySQL:

MySQL: How to Select Rows where Date is Equal to Today

Cite this article

mohammed looti (2026). How to Add Hours to a Datetime in MySQL. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-hours-be-added-to-a-datetime-in-mysql/

mohammed looti. "How to Add Hours to a Datetime in MySQL." PSYCHOLOGICAL SCALES, 5 Jan. 2026, https://scales.arabpsychology.com/stats/how-can-hours-be-added-to-a-datetime-in-mysql/.

mohammed looti. "How to Add Hours to a Datetime in MySQL." PSYCHOLOGICAL SCALES, 2026. https://scales.arabpsychology.com/stats/how-can-hours-be-added-to-a-datetime-in-mysql/.

mohammed looti (2026) 'How to Add Hours to a Datetime in MySQL', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-hours-be-added-to-a-datetime-in-mysql/.

[1] mohammed looti, "How to Add Hours to a Datetime in MySQL," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, January, 2026.

mohammed looti. How to Add Hours to a Datetime in MySQL. PSYCHOLOGICAL SCALES. 2026;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top