Syntax error How to get the Average on MySQL time column?

How to get the Average on MySQL time column?



To get average on time column, use the below syntax. It will give the average in time format −

SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(yourColumnName))) as anyVariableName from yourTableName;

To understand the above concept, let us create a table. The following is the query −

mysql> create table AverageOnTime
   −> (
   −> PunchInTime time
   −> );
Query OK, 0 rows affected (0.61 sec)

Insert time values in the table using insert command. The query to insert records is as follows −

mysql> insert into AverageOnTime values('00:00:40');
Query OK, 1 row affected (0.20 sec)

mysql> insert into AverageOnTime values('00:02:50');
Query OK, 1 row affected (0.15 sec)

mysql> insert into AverageOnTime values('00:03:30');
Query OK, 1 row affected (0.13 sec)

mysql> insert into AverageOnTime values('00:04:55');
Query OK, 1 row affected (0.14 sec)

Display time from the table using select statement. The query is as follows −

mysql> select *from AverageOnTime;

The following is the output −

+-------------+
| PunchInTime |
+-------------+
| 00:00:40    |
| 00:02:50    | 
| 00:03:30    |
| 00:04:55    |
+-------------+
4 rows in set (0.00 sec)

Now to get the average on time column, use the below query. The query is as follows −

mysql> SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(PunchInTime))) as Average from AverageOnTime;

The following is the output displaying the average -

+---------------+
| Average       |
+---------------+
| 00:02:58.7500 |
+---------------+
1 row in set (0.08 sec)
Updated on: 2019-07-30T22:30:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements