I tried to do the following:
CREATE TABLE test_table
(
column_1 varchar(255),
column_2 varchar(255),
combined varchar(255) DEFAULT concat(column_1, '_', column_2)
);
It produces the following error:
ERROR: cannot use column reference in DEFAULT expression
This similar question uses an update query for the entire table: Insert value into a column in PostgreSQL
I would like to know if there is a way to do this as part of the insert?
With the following as an example of input and expected output:
insert into test_table ('column_1', 'column_2')
values ('Alpha', 'Beta')
select * from test_table;
('Alpha', 'Beta', 'Alpha_Beta')
Notes:
- Inputs are always strings
- They will likely always be under 20 characters
- I can't create a https://dbfiddle.uk/HuZKDYgb because I don't know how to create the table
Conclusion The answers by @JoeStefanelli and @Charlieface both answer the question with the original intention in mind of having a third column with the composite value. I think that the answer by @jarlh may actually be more optimal though? By using the view the duplicate information is not stored in the database. Also in my case I know that the inputs will never be null or empty, I did not think to include that in the initial question though as I was focused on the combined value solution.
GENERATED ALWAYS Solutions:
VIEW Solution:
GENERATED ALWAYS AS ( generation_expr ) STORED |. This works in all currently supported Postgres versions 13+.GENERATEDcolumn workinsert into test_table (column_1, column_2, combined) values ('Alpha', 'Beta', 'different')to insert?