1

I have a table t with the column c. The column c has a default value.

create table t (c text default 'a');

I can insert the default value.

insert into t (c) values (default);

Now I want to do insert the value of a variable into the table. And if the variable is null, I want to insert the default value.

do $$declare
  v text;
begin
  insert into t (c) values (coalesce (v, default));
end$$;

But It does not work.

ERROR: DEFAULT is not allowed in this context

How to work around this? Do I need two different insert statements?

ceving
  • 21,900
  • 13
  • 104
  • 178
  • You could query the default value for that column (see: https://stackoverflow.com/questions/8146448/get-the-default-values-of-table-columns-in-postgres) and use that value in stead of `default`. – Luuk Jul 20 '21 at 11:44

0 Answers0