How to sum time in MySQL by converting into seconds?

MySQLMySQLi Database

To convert time to seconds, use the TIME_TO_SEC() method. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ArrivalTime time
   -> );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('04:10:00');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('05:20:50');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('06:40:10');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------------+
| ArrivalTime |
+-------------+
| 04:10:00    |
| 05:20:50    |
| 06:40:10    |
+-------------+
3 rows in set (0.00 sec)

Following is the query to calculate the sum of time in MySQL −

mysql> select SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) from DemoTable;

Output

+-------------------------------------------------+
| SEC_TO_TIME( SUM( TIME_TO_SEC( ArrivalTime) ) ) |
+-------------------------------------------------+
| 16:11:00                                        |
+-------------------------------------------------+
1 row in set (0.00 sec)
raja
Published on 09-Jul-2019 12:47:00
Advertisements