0

How can I tell Postgres that a column with an empty string should use the DEFAULT value?

Using CHECK doesn't seem to work here.

5
  • In short: you can't. An empty string is still a valid value for a varchar column. NULL is not a value. You could add a constraint forbidding the string length being < 1. Commented Jan 19, 2014 at 11:35
  • Currently I use a check NOT NULL CHECK (status <> '') DEFAULT 'active' Commented Jan 19, 2014 at 11:37
  • That looks Ok, it will prevent empty strings to be inserted. If you don't want empty strings, you (or your frontend program) should not want to insert them in the first place. Commented Jan 19, 2014 at 11:42
  • Of course, I just wanted to enforce this constraint on the lowest level possible, which is ultimately the DB. Commented Jan 19, 2014 at 12:00
  • If you want this type of constraint in more than one place, you could consider making it a domain, avoiding code duplication. Commented Jan 19, 2014 at 12:03

1 Answer 1

1

A check constraint will only prevent putting such a value into the column. It will not magically replace the supplied value with the default value.

In order to silently replace an empty string (or null) with the value 'active' you will need a trigger:

create or replace function check_default()
 returns trigger
as
$body$
begin
   if (new.status is null or new.status = '') then
      new.status = 'active';
   end if;
   return new;
end;
$body$
language plpgsql;

The above trigger would catch stuff like this:

insert into foo (id, active) 
values (42,'');

update foo 
  set active = ''
where id = 42;

You could even extend that logic to also replace whitespace only values (' ') with the desired value.

Although it is possible to retrieve the default value dynamically in the trigger (to avoid having the same constant in two places) I would not do that for performance reasons.

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.