简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM