Re: unique constraint - bug?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Merrill Oveson <merrill(at)actarg(dot)com>
Cc: pgsql-general(at)postgresql(dot)org, Kyle Bateman <kyle(at)actiontarget(dot)com>
Subject: Re: unique constraint - bug?
Date: 2000-07-20 04:12:32
Message-ID: 22938.964066352@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Merrill Oveson <merrill(at)actarg(dot)com> writes:
> It appears as though the null value inserted for column b causes an
> abrogation of the unique constaint.

Two nulls are never considered equal, therefore the unique constraint
does not trigger.

This is correct behavior according to SQL92 4.10.2:

A unique constraint is satisfied if and only if no two rows in
a table have the same non-null values in the unique columns. In
^^^^^^^^
addition, if the unique constraint was defined with PRIMARY KEY,
then it requires that none of the values in the specified column or
columns be the null value.

(The second sentence just says that PRIMARY KEY implies NOT NULL as well
as UNIQUE.)

Another way to look at it is that the comparison to see whether the two
NULLs are equal would yield NULL, and a NULL result for a constraint
condition is not considered to violate the constraint.

Another way to look at it is that NULL means "I don't know what the
value is", so if you don't know what the values in two rows really are,
you don't know whether they're equal either. I suppose you could make
a case for either accepting or rejecting the UNIQUE constraint in that
situation --- but SQL92 chose the "accept" decision, and I think that
for the majority of practical applications they made the right choice.

If you don't like that behavior, possibly your column should be defined
as NOT NULL.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2000-07-20 04:22:49 Re: [HACKERS] Re: PRIMARY KEY & INHERITANCE (fwd)
Previous Message Stephan Szabo 2000-07-20 00:50:06 Re: Re: [GENERAL] PRIMARY KEY & INHERITANCE (fwd)