MySQL – Formatting Text Field as HH:MM:SS

MySQLquery

I am having to Cast() a Text datatype to a TIME datatype. THe issue I'm running into is when the results display i'm loosing the hh:mm:ss format. The syntax I am using is Select SUM(CAST(salestime As Time)) From testData; How do I display my query results in hh:mm:ss format? I also tried to use this syntax SUM(Cast(Time_Format(salesTime, "%h, %i, %s") As Time)) but that is returning a whole number

EDIT
A few sample of the times in the TEXT column are:

0:05:58
0:00:00
0:31:54
0:23:26

Best Answer

You can use this

Schema (MySQL v8.0)

CREATE TABLE Table1
    (`salesTime` varchar(7))
;
    
INSERT INTO Table1
    (`salesTime`)
VALUES
    ('0:05:58'),
    ('0:00:00'),
    ('0:31:54'),
    ('0:23:26')
;

Query #1

SELECT SEC_TO_TIME( SUM( TIME_TO_SEC(TIME_FORMAT(`salesTime`, "%H:%i:%s"))))  FROM Table1;

| SEC_TO_TIME( SUM( TIME_TO_SEC(TIME_FORMAT(`salesTime`, "%H:%i:%s")))) |
| --------------------------------------------------------------------- |
| 01:01:18                                                              |

View on DB Fiddle

But TIME can only have the maximum of 838:59:59, if your SUM get bigger, you need to convert the seconds also into dd.hh:mm:ss