Allow null in unique column

前端 未结 6 1522
走了就别回头了
走了就别回头了 2020-12-08 02:13

I\'ve created the following table:

CREATE TABLE MMCompany (
   CompanyUniqueID BIGSERIAL PRIMARY KEY NOT NULL, 
   Name VARCHAR (150) NOT NULL,
   PhoneNumb         


        
6条回答
  •  無奈伤痛
    2020-12-08 02:35

    Unique and null don't get along much, since null is undefined by definition — you can't know if two nulls are the same unknown.

    In this sense, your current unique constraint on email is the right thing to do and should work as is.


    In case you ever need to make it otherwise, though, a partial index works:

    create unique index on MMCompany((email is null)) where (email is null);
    

    Another approach is to define a constraint trigger. Something like:

    create function email_chk() returns trigger as $$
    begin
      if exists (
        select 1 from mmcompany where email is null and companyuniqueid <> new.id
      ) then
        raise 'dup null found';
      end if;
      return null;
    end;
    $$ language plpgsql;
    
    create constraint trigger after insert or update on mmcompany
    for each row when (new.email is null)
    execute procedure email_chk();
    

提交回复
热议问题