Mastering MySQL TIME Data Type
The TIME data type in MySQL is used to store time values (HH:MM:SS format). It is useful for representing durations, time of day, or intervals without any associated date.
1. Understanding TIME Data Type
Feature | Details |
---|---|
Format | 'HH:MM:SS' |
Storage | 3 bytes |
Range | '-838:59:59' to '838:59:59' |
Default Value | '00:00:00' (if NOT NULL is not specified) |
✔ Supports negative values for time differences.
✔ Can store values greater than 24 hours, unlike some other databases.
2. Creating a Table with TIME Column
✔ The task_time
column must be manually set when inserting records.
3. Inserting TIME Values
✔ TIME values must be in 'HH:MM:SS'
format.
Using SEC_TO_TIME()
to insert a computed duration:
4. Retrieving and Formatting TIME Values
Fetch all records:
Format TIME output:
✔ Converts '08:30:00' → '08:30 AM'.
5. Updating TIME Values
Change the task time:
✔ Updates the time value.
6. Working with TIME Arithmetic
Adding and Subtracting Time
Add 2 hours to a time:
Subtract 30 minutes:
Finding Time Differences
Find the time difference between the two times:
Convert a time into total seconds:
7. Comparing TIME Values
Find tasks scheduled after 10 AM:
Find all tasks scheduled before now:
✔ CURTIME()
returns the current time.
8. Extracting Parts of a TIME Value
- Get the hour:
- Get the minutes:
- Get the seconds:
9. Converting TIME to Other Formats
Convert TIME to hours and minutes:
✔ Converts '08:30:00' → '08:30 AM'.
Convert TIME to decimal hours:
✔ Converts '02:30:00' → 2.5 hours.
10. Summary
- TIME stores values from -838:59:59 to 838:59:59.
- Use TIME_FORMAT() for custom display formats.
- Use ADDTIME() and SUBTIME() for time calculations.
- Use TIMEDIFF() to find differences between two TIME values.
- Use TIME_TO_SEC() and SEC_TO_TIME() for conversions.
Would you like to see examples of real-world use cases, such as tracking work hours or logging durations? 🚀