sqlpostgresql

Return time difference in the format hh:mm:ss in SQL


I need to return the total air flight in the hh:mm:ss format. The departure time and arrival time are both in the following format:

2024-05-05T10:30:00

I tried the code below and got the message:

SELECT
    departure_city,
    arrival_city,
    DATEDIFF(departure_time, arrival_time),
    (
        SELECT
        CAST(arrival_time as time),
        CAST(departure_time as time)
        FROM flight
    )
FROM flight

Error function datediff(timestamp without time zone, timestamp without time zone) does not exist LINE 4: DATEDIFF(departure_time, arrival_time), ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts.

enter image description here


Solution

  • Your syntax is completely off. It doesn't even start to make sense in any SQL dialect I know of. Why the subquery, what is that supposed to do?

    In Postgres you can subtract two dates to get an interval. That can then be formatted using to_char.

    SELECT
        departure_city,
        arrival_city,
        arrival_time - departure_time AS duration,
        to_char(arrival_time - departure_time, 'HH24:MI:SS') AS duration_formatted
    FROM flight;
    

    If the number of hours could be more than 24 then it's alittle more involved

    case when arrival_time - departure_time > interval '1d'
        then to_char(justify_hours(arrival_time - departure_time), 'DDD HH24:MI:SS')
        else to_char(justify_hours(arrival_time - departure_time), 'HH24:MI:SS')
    end