0

Let's assume a table t:

create table if not exists t(
    a integer primary key generated by default as identity,
    b integer,
    c text
);

and simple insert insert into t (b, c) values (2, 'abc'); Is there any option how to rewrite this insert and as a result in column b will be coalesce(b, a)? So when b is null, b equals to generated column a.

I know there is an option to use RETURNING keyword and update or to use before insert trigger.

1
  • 1
    No:insert into t (b, c) values (coalesce(null, a), 'abc'); HINT: There is a column named "a" in table "t", but it cannot be referenced from this part of the query. Commented Feb 10, 2021 at 20:40

1 Answer 1

1

What you intend to do introduces redundancy, so I recommend that you don't do it. Rather, use coalesce wjen you query the table. A convenient solution would be a view on the table that does that.

If you insist on persisting that in the table, you will have to use a trigger.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.