NULLL comparison in multiple column unique index

From: "Brian Walker" <brianw(at)mcsdallas(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: NULLL comparison in multiple column unique index
Date: 2003-01-02 23:19:52
Message-ID: 200301021719520868.01EFA8DC@mail.mcsdallas.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I have an application currently running under MSSQL and I am in the process of porting it to PostgreSQL.

I am having a problem with differences in MSSQL and PostgreSQL in relation to NULL columns with a multiple column unique index.

Here is my test script.

create table test1 (name varchar(64),num1 int,num2 int);
create unique index idx1 on test1(name,num1);
insert into idx1 values('row1',10,20);
insert into idx1 values('row2',11,21);

So "insert into idx1 values ('row2',11,50)" will fail which is what I want.

My problem is that sometimes the value of "num1" will be NULL for a column. This is because in my application these are foreign keys into another table. So if I do this:

insert into idx1 values ('row3',null,22);

then I do this again:

insert into idx1 values ('row3',null,23);

This is allowed to happen. In Microsoft SQL the second insert will fail because of the unique index. This looks like in MSSQL for the unique index checks that NULL is equal to NULL so the unique check fails. In PostgreSQL NULL != NULL so the unique check passes because even though the name is the same the "num1" field is different..

Does anybody have any ideas on how I can work around this difference?

Thanks

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Bhuvan A 2003-01-03 05:20:57 Re: Adding a Primary Key to an exisiting table
Previous Message Maly Kaing 2003-01-02 21:15:32 Adding a Primary Key to an exisiting table