Search code examples
sqlhsqldb

sql Alter table: create a column base on datediff between 2 columns


I want to creat a computed column based on datediff function between 2 existing columns (date1 and date2). (in days)

date1 and date2 are sql DATE type.

What I tried without sucess :

     ALTER TABLE my_table ADD lenght AS datediff('dd', date1, date2)

Thank you for helping.


Solution

  • A GENERATED column is automatically updated when the values it refers to in other columns change. The correct syntax is:

    ALTER TABLE my_table ADD length INT GENERATED ALWAYS AS (DATEDIFF('day', date1, date2))