'SQL: Default value of a column to be addition of two columns

I have a table with columns like net and vat, I wanted to add a new column to the table called total, which should be by default the addition of net + vat... I am using Postgres as the database, is it possible to do what I expect?



Solution 1:[1]

If you are using Potsgres 12 or later, you can add a generated column:

alter table the_table
   add total numeric generated always as (net + vat) stored;

Complete example online

Another solution for such a simple derived attribute is to create a view:

create view the_table_with_total
as
select <other columns>, net + vat as total
from the_table;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 a_horse_with_no_name