PostgreSQL autogenerated interval
Using postgres specific SQL syntax we can create autogenerated column which subtracts two dates and stores them as interval.
The age
function is also null-safe, so if time_ended
or time_started
it will not crash.
ALTER TABLE session ADD COLUMN
duration interval GENERATED ALWAYS AS (age(time_ended, time_started)) STORED;