Search code examples
sqlpostgresqlddl

SQL : How to create a table with auto-computed column values?


Problem : Trying to create a column named 'duration' that auto-inserts its value based on the difference of the columns 'start_time' and 'end_time'.

SQL Dialect : PostgreSQL

Here's what I've tried

CREATE TABLE my_table_example (
    start_time BIGINT,
    end_time BIGINT,
    duration BIGINT AS DIFFERENCE(start_time, end_time)
)

Question : Using SQL DDL How do you auto-compute the value of the difference of two other columns as its value in an SQL 'CREATE TABLE' statement?

Goal : Example of what table should look like on SQL insert statement

insert into my_table_example (1, 2)

insert into my_table_example (2, 5)

insert into my_table_example (1, 7)

my_table_example
+------------+-----------+----------+
| start_Time | end_time  | duration |
+------------+-----------+----------+
|     1      |     2     |    1     |
|     2      |     5     |    3     |
|     1      |     7     |    6     | 
+------------+-----------+----------+

Solution

  • You could have tried the manual...

    CREATE TABLE my_table_example (
        start_time timestamp,
        end_time timestamp,
        duration interval GENERATED ALWAYS AS ( end_time - start_time ) STORED
    );
    
    INSERT INTO my_table_example(start_time, end_time) 
    VALUES ('2023-10-01 23:00', '2023-10-02 14:00') 
    RETURNING *;