0

I'm new to SQL and PostgreSQL and I'm trying to find a way to create a new table in database where a column will automatically calculate a pre-defined function with data from other columns.

Specifically I want a LOG table with TIME_IN | TIME_OUT | DURATION columns where the DURATION column shows the result of (=TIME_OUT - TIME_IN)

Of course this can be done with running a query but I'm trying to figure out if it's possible

to have it pre-defined so whenever running SELECT * FROM log the table will load up with duration value already calculated according to updated data in IN / OUT columns.

asked Aug 1, 2021 at 14:50

1 Answer 1

2

This can be done using a generated column, e.g.:

create table log
( 
 id integer primary key generated always as identity,
 time_in timestamp,
 time_out timestamp,
 duration interval generated always as (time_out - time_in) stored
);

Another option would be to create a view:

create view log_with_duration
as
select id, 
 time_in, 
 time_out, 
 time_out - time_in as duration
from log;
answered Aug 1, 2021 at 14:55
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.