I need to create unique index for table with two fields (email, alternative_email). It means one email address can be mentioned only one time in two columns. Also alternative email can be empty.
CREATE TABLE customers (
id serial PRIMARY KEY,
email VARCHAR (255) NOT NULL,
alternative_email VARCHAR (255) NOT NULL default ''
);
Data:
insert into customers (email, alternative_email)
values ('[email protected]', ''); - ok
insert into customers (email, alternative_email)
values ('[email protected]', '[email protected]');
Second row should not be inserted because alternative_email = '[email protected]' already mentioned as email in first row.
How to create index to do this ?
NOT NULL default ''seems like an odd choice if you don't require an alternative emailcreate unique index on customers ( (coalesce(nullif(alternative_email, ''), email)));