You are viewing a plain text version of this content. The canonical link for it is here.
Posted to derby-user@db.apache.org by Michael Segel <ms...@segel.com> on 2005/11/02 08:34:54 UTC

Derby and other RDBMS handling constraints and NULLS.

I lost my DB server that was also my mail server to a melt down. (You can only 
keep those INTEL CPUs running with poor airflow for only so long... ;-)
[3 1/2 years or so?] So I had to go out and build a new server from the ground 
up....


Problem Statement:
How do databases handle unique constraints placed upon their objects and 
NULLs.

The issue arose that Sybase allows one to place a unique constraint on a 
table, yet will allow duplicate records iff (if and only if) one of the 
constraint columns has null value.  

As per one of Daniel's posts the test for a unique constraint is to do an 
inner select to see if the row already exists. If the inner select fails to 
find any rows, then its ok to insert the row.

The problem is when you have an instance of NULL.
here's a good link to explain NULLS: 
:http://www.sqlservercentral.com/columnists/mcoles/fourrulesfornulls_printversion.asp

Now with respect to unique constraints, they can be applied on either indexes 
or on tables.

For each database we need to review the consistency between how the database 
handles uniqueness in both the table clause and unique indexes.

DERBY:
	Derby does not allow NULLs in columns that are part of a unique table 
constraint. So this begs the question all together. No NULL values. However, 
you can create a unique index on a set of columns even when one is null.
The result is that you can create a unique index, however you can only have 
one row where an element can be NULL.

NOTE: Derby is INCONSISTENT with its treatments of UNIQUENESS on Indexes and 
Tables.

INFORMIX:
	Informix does allow you to create a table constraint including columns that 
contain NULL. It will also allow you to create a row that contains null, 
however it will not allow for duplicate NULLs.  When a Unique constraint is 
applied to an index you can create an index that contains NULLS, however you 
can not create duplicates.

NOTE: INFORMIX is CONSISTANT in how it handles NULLS when working on Unique 
Constraints on either Indexes or Tables. (I didn't try a column but I'm sure 
it will be the same..

I was going to do it again on DB2, but alas, my machine melted.
And we have heard Sybase handles it differently.


THE BOTTOM LINE:

In designing a database, you need to apply the KISS principle. (Thats Keep It 
Simple Stupid.) Its a real engineering term and on the deserves respect.
So in database design, we want to consistently treat NULLS along with how you 
apply constraints across containers.

This consistency will clean up and simplify your design, allowing for more 
complex issues to be implemented within a more efficient footprint.

Now having said all that, if the ANSI Standard Base were to allow for multiple 
NULLS within a UNIQUE constraint, or a unique index, It would be a pretty 
lame and bad idea. 

In fact, how can you generate an unique index with multiple NULL values?
(Hint: NULL A != NULL B, so NULL != NULL, yet since NULL represents the 
unknown set,  Try creating an unique index with having multiple tupples that 
contain NULL and the same non-null tupple. ;-)

Another important design consideration: Which takes precedence: SQL Statements 
that manipulate your containters, or ones that manipulate the data stored in 
the containers? And Why? ;-)

If you code properly, you should have a clean system.

Again, Sybase's code is a bug. 
Also with respect to the snippet posted by Junior, it doesn't handle nulls 
properly. In fact, it never addresses Nulls.

Read that URL I included.
Also think about a Scrodinger's Cat.

MEOW! ;-)

But hey, what do I know ? ;-)

You can try other databases and you'll find that they will uniquely interpret 
ANSI SQL 92.

-G 
Think before you post. ;-)

-- 
Michael Segel
Principal 
MSCC

Re: Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by "Bernt M. Johnsen" <Be...@Sun.COM>.
>>>>>>>>>>>> Mike Matrigali wrote (2005-11-02 09:06:21):
> Bernt, could you explain below a little more.  I don't understand
> what it means for the columns with null values are not part of
> the index?  Do you mean the rows with columns with null values?

I mean columns with null values in nullable columns used in a unique
index. In the example below

(NULL, 1, 1) would not be in idx1
(1, 1, NULL) would not be in idx2
(NULL, 1, NULL) would not be in any of them

> 
> Bernt M. Johnsen wrote:
> 
> >Appendix A: A note on implementation
> >================================================== 
> >
> >For those wondering how unique indices with multiple null values may
> >be implemented, it can be done pretty simple: The columns with null
> >values are not part of the index. This will if course affect the
> >execution plan.
> >
> >Example:
> >
> >CREATE TABLE t (i INTEGER, a INTEGER NOT NULL, b INTEGER);
> >CREATE UNIQUE INDEX idx1 ON t(i);
> >CREATE UNIQUE INDEX idx2 ON t(a, b);
> >
> >SELECT i FROM t WHERE i=1;       -- Use index idx1
> >SELECT i FROM t WHERE i IS NULL; -- Do a table scan
> >SELECT a FROM t WHERE a=5;       -- Do a table scan
> >SELECT a FROM t WHERE a=5 AND b IS NOT NULL;
> >                                 -- Use index idx2
> >
> >There is of course are other ways of implementing unique indices with
> >multiple null values.
> 

-- 
Bernt Marius Johnsen, Database Technology Group, 
Sun Microsystems, Trondheim, Norway

Re: Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by Mike Matrigali <mi...@sbcglobal.net>.
Bernt, could you explain below a little more.  I don't understand
what it means for the columns with null values are not part of
the index?  Do you mean the rows with columns with null values?

Bernt M. Johnsen wrote:

> Appendix A: A note on implementation
> ================================================== 
> 
> For those wondering how unique indices with multiple null values may
> be implemented, it can be done pretty simple: The columns with null
> values are not part of the index. This will if course affect the
> execution plan.
> 
> Example:
> 
> CREATE TABLE t (i INTEGER, a INTEGER NOT NULL, b INTEGER);
> CREATE UNIQUE INDEX idx1 ON t(i);
> CREATE UNIQUE INDEX idx2 ON t(a, b);
> 
> SELECT i FROM t WHERE i=1;       -- Use index idx1
> SELECT i FROM t WHERE i IS NULL; -- Do a table scan
> SELECT a FROM t WHERE a=5;       -- Do a table scan
> SELECT a FROM t WHERE a=5 AND b IS NOT NULL;
>                                  -- Use index idx2
> 
> There is of course are other ways of implementing unique indices with
> multiple null values.


Re: Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by Mike Matrigali <mi...@sbcglobal.net>.

Jeffrey Lichtman wrote:
> 
>> > CREATE TABLE t2 (i INTEGER, j INTEGER NOT NULL);
>> > CREATE INDEX idx3 on t2(i);
>> > CREATE UNIQUE INDEX idx4 on t2(j);
>> >
>> > SELECT i FROM t2;  -- use index idx3 (covers query)
>> > SELECT j FROM t2;  -- Do a table scan
>>
>> Shouldn't the last SELECT use idx4 since the index is UNIQUE *and* j
>> is NOT NULL?
>> -- 
>> Bernt Marius Johnsen, Database Technology Group,
> 
> 
> Yes, you're right. I should have said:
> 
> CREATE TABLE t2 (i INTEGER, j INTEGER);
> CREATE INDEX idx3 on t2(i);
> CREATE UNIQUE INDEX idx4 on t2(j);
> 
> SELECT i FROM t2;  -- use index idx3 (covers query)
> SELECT j FROM t2;  -- Do a table scan
> 
> I've done a little more thinking about this problem. I suspect that the 
> store code uses the results of the same compare() method invocation to 
> determine where to insert a row into an index and also to determine 
> whether the row is a duplicate in a unique index. If Derby is to allow 
> multiple nulls in a unique index, the store must use the two different 
> null semantics for the two cases. For the question of where to insert 
> the row, nulls must be considered to be equal to each other, and for the 
> question of whether they are duplicates, they must be considered not 
> equal to each other.
> 
> If I'm right, it should be easy to change Derby to allow multiple nulls 
> in unique indexes. We still haven't heard from any of the store experts, 
> though. Mike?

I haven't thought this one all the way through, but thought I would
respond with at least what I know - I have been reticent to weigh
in on this uniqueness issue given the flack being thrown about.  So
I asked for some patience if I say something stupid below.

When I last looked at this issue
I looked at special casing columns with null's in the unique index and
that turned into a rat hole where all unique key index lookups would
go slower to support the multiple null case.

The current derby index implementation assumes all rows in the index are
unique and have a deterministic ordering, where a row in the index is 
all the key columns plus the the row location column which points to the
row in the base table.  So for "non-unique" indexes searching is always
done using all columns plus the row location column.  This basic 
assumption is used for searching, branch key specification, logical
undo recovery, and serializable locking considerations.  So from store
point of view during searching null's must compare equal.

For unique indexes searching is done using only the keys, and not the
the row location column.  In this way when a search is done to insert
a row into the unique index, it searches just for the keys (not 
including the unique row location) and if it
finds an existing non-deleted match it throws a duplicate key exception.

As jeff points out there may be a way to do the search using one compare
and the duplicate check using another, but no matter what from the store
point of view the null's are the same (yes I know SQL does not agree).
Recovery on a unique key index expects that searching for a key will
find ONE entry for the key and it will be the right one.  There are also
locking, searching and cost assumptions/optimizations that assume if you 
are looking for a key in the tree you will only get 1 row back.

So I think if it were decided to allow multiple null's in a constraint
or an index, then the actual underlying btree implementation to use 
would be the non-unique index implementation with some extra code
stuck in to do the datatype specific comparison necessary at insert 
time.  I think that code would look something like:
     o position beginning of scan using insert key, using current 
compare semantics.
     o scan all rows which match the key using current semantics
     o for each row use alternate compare semantics and if alternate
       compare says equal disallow insert.

This could be
done today with no store changes by having the execution engine first
do a serializable lookup on the row to be inserted and then inserting
if the row met SQL defined uniqueness definitions - but implementing
in store would be more efficient as at least it would only do one
search vs. 2.

I would worry about an implementation like the one Bernt suggests, as it
just seems to invite weird bugs when using the wrong index; but this
may just reflect my inexperience with the optimizer and execution engine.

The other day I heard a good use for the SQL constraint null semantics.
Imagine an application that tracked people by SS# but also included
people with no SS#.  In that case the SQL constraint would insure
uniqueness of the SS# while allowing null's for those with no SS#.

> 
>                        -        Jeff Lichtman
>                                 swazoo@rcn.com
>                                 Check out Swazoo Koolak's Web Jukebox at
>                                 http://swazoo.com/
> 
> 


Re: Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by Jeffrey Lichtman <sw...@rcn.com>.
> > CREATE TABLE t2 (i INTEGER, j INTEGER NOT NULL);
> > CREATE INDEX idx3 on t2(i);
> > CREATE UNIQUE INDEX idx4 on t2(j);
> >
> > SELECT i FROM t2;  -- use index idx3 (covers query)
> > SELECT j FROM t2;  -- Do a table scan
>
>Shouldn't the last SELECT use idx4 since the index is UNIQUE *and* j
>is NOT NULL?
>--
>Bernt Marius Johnsen, Database Technology Group,

Yes, you're right. I should have said:

CREATE TABLE t2 (i INTEGER, j INTEGER);
CREATE INDEX idx3 on t2(i);
CREATE UNIQUE INDEX idx4 on t2(j);

SELECT i FROM t2;  -- use index idx3 (covers query)
SELECT j FROM t2;  -- Do a table scan

I've done a little more thinking about this problem. I suspect that 
the store code uses the results of the same compare() method 
invocation to determine where to insert a row into an index and also 
to determine whether the row is a duplicate in a unique index. If 
Derby is to allow multiple nulls in a unique index, the store must 
use the two different null semantics for the two cases. For the 
question of where to insert the row, nulls must be considered to be 
equal to each other, and for the question of whether they are 
duplicates, they must be considered not equal to each other.

If I'm right, it should be easy to change Derby to allow multiple 
nulls in unique indexes. We still haven't heard from any of the store 
experts, though. Mike?

                        -        Jeff Lichtman
                                 swazoo@rcn.com
                                 Check out Swazoo Koolak's Web Jukebox at
                                 http://swazoo.com/ 


Re: Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by "Bernt M. Johnsen" <Be...@Sun.COM>.
>>>>>>>>>>>> Jeffrey Lichtman wrote (2005-11-02 11:46:30):
> 
> Here are some more examples, assuming that nulls are not stored in indexes:
> 
> CREATE TABLE t2 (i INTEGER, j INTEGER NOT NULL);
> CREATE INDEX idx3 on t2(i);
> CREATE UNIQUE INDEX idx4 on t2(j);
> 
> SELECT i FROM t2;  -- use index idx3 (covers query)
> SELECT j FROM t2;  -- Do a table scan

Shouldn't the last SELECT use idx4 since the index is UNIQUE *and* j
is NOT NULL?

-- 
Bernt Marius Johnsen, Database Technology Group, 
Sun Microsystems, Trondheim, Norway

Re: Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by Jeffrey Lichtman <sw...@rcn.com>.
>For those wondering how unique indices with multiple null values may
>be implemented, it can be done pretty simple: The columns with null
>values are not part of the index. This will if course affect the
>execution plan.
>
>Example:
>
>CREATE TABLE t (i INTEGER, a INTEGER NOT NULL, b INTEGER);
>CREATE UNIQUE INDEX idx1 ON t(i);
>CREATE UNIQUE INDEX idx2 ON t(a, b);

Here are some more examples, assuming that nulls are not stored in indexes:

CREATE TABLE t2 (i INTEGER, j INTEGER NOT NULL);
CREATE INDEX idx3 on t2(i);
CREATE UNIQUE INDEX idx4 on t2(j);

SELECT i FROM t2;  -- use index idx3 (covers query)
SELECT j FROM t2;  -- Do a table scan


>There is of course are other ways of implementing unique indices with
>multiple null values.
>--
>Bernt Marius Johnsen, Database Technology Group,

Yes. The comparison operations for datatypes are defined in the interface:

org.apache.derby.iapi.types.DataValueDescriptor

This interface defines two comparison methods:


         /**
          * Compare this Orderable with a given Orderable for the purpose of
          * index positioning.  This method treats nulls as ordered values -
          * that is, it treats SQL null as equal to null and less than all
          * other values.
          *
          * @param other         The Orderable to compare this one to.
          *
          * @return  <0 - this Orderable is less than other.
          *                       0 - this Orderable equals other.
          *                      >0 - this Orderable is greater than other.
      *
      *                  The code should not explicitly look for -1, or 1.
          *
          * @exception StandardException         Thrown on error
          */
         int compare(DataValueDescriptor other) throws StandardException;

         /**
          * Compare this Orderable with a given Orderable for the purpose of
          * qualification and sorting.  The caller gets to determine how nulls
          * should be treated - they can either be ordered values or unknown
          * values.
          *
          * @param op    Orderable.ORDER_OP_EQUALS means do an = comparison.
          *                              Orderable.ORDER_OP_LESSTHAN 
means compare this < other.
          * 
Orderable.ORDER_OP_LESSOREQUALS means compare this <= other.
          * @param other The DataValueDescriptor to compare this one to.
          * @param orderedNulls  True means to treat nulls as ordered values,
          *                                              that is, 
treat SQL null as equal to null, and less
          *                                              than all other values.
          *                                              False means 
to treat nulls as unknown values,
          *                                              that is, the 
result of any comparison with a null
          *                                              is the 
UNKNOWN truth value.
          * @param unknownRV             The return value to use if 
the result of the
          *                                              comparison 
is the UNKNOWN truth value.  In other
          *                                              words, if 
orderedNulls is false, and a null is
          *                                              involved in 
the comparison, return unknownRV.
          *                                              This 
parameter is not used orderedNulls is true.
          *
          * @return      true if the comparison is true (duh!)
          *
          * @exception StandardException         Thrown on error
          */
         boolean compare(
     int         op,
     DataValueDescriptor   other,
     boolean     orderedNulls,
     boolean     unknownRV)
                                 throws StandardException;

I don't know which compare method the store uses to determine 
uniqueness of a data value for a unique index. I suspect it either 
uses the first, or it uses the second with orderedNulls equal to 
TRUE. In any case, the interface already supports a technique to 
allow multiple nulls in a unique index. There may be some reason the 
store can't use this technique, though.


                        -        Jeff Lichtman
                                 swazoo@rcn.com
                                 Check out Swazoo Koolak's Web Jukebox at
                                 http://swazoo.com/ 


Derby, SQL 2003, UNIQUE constraints, unique indices and NULL (long)

Posted by "Bernt M. Johnsen" <Be...@Sun.COM>.
Contents:
============================================================
0. Introduction
1. The standard
2. Conclusion
Appendix A: A note on implementation


0. Introduction
============================================================

There's been a lot of discusion around the use of UNIQUE and
nullability in Derby so I decided to walk through the standards and
find what they say (regardless what Sybase, Informix, DB2, Oracle and
other databases may have implemented) and then draw my conclusions.


1. The standard
============================================================

The definition of NULL in ISO/IEC 9075-1:2003 (E) SQL 2003 Part 1 -
SQL/Framework, p. 15 is:

    4.4.2 The null value

    Every data type includes a special value, called the null value,
    sometimes denoted by the keyword NULL. This value differs from
    other values in the following respects:

    -- Since the null value is in every data type, the data type of
       the null value implied by the keyword NULL cannot be inferred;
       hence NULL can be used to denote the null value only in certain
       contexts, rather than everywhere that a literal is permitted.

    -- Although the null value is neither equal to any other value nor
       not equal to any other value -- it is unknown whether or not it
       is equal to any given value -- in some contexts, multiple null
       values are treated together; for example, the <group by clause>
       treats all null values together.

Furthermore, whether to allow nullable columns is an optional feature
and not a part of SQL 2003 Mandatory (nor of SQL 99 Core): (ISO/IEC
9075-2:2003 (E) SQL 2003 Part 2 - SQL/Foundation, p. 1161)

    189) Specifications for Feature T591, "UNIQUE constraints of
         possibly null columns": 

         a) Subclause 11.7, "<unique constraint definition>":

            i) Without Feature T591, "UNIQUE constraints of possibly
            null columns", in conforming SQL language, if UNIQUE is
            specified, then the <column definition> for each column
            whose <column name> is contained in the <unique column
            list> shall contain NOT NULL. 

            NOTE 484 - The Conformance Rules of Subclause 9.10,
            "Grouping operations", also apply.


The UNIQUE constraint is defined as follows (ISO/IEC 9075-2:2003 (E)
SQL 2003 Part 2 - SQL/Foundation, p. 568):

    2) The unique constraint is not satisfied if and only if
           EXISTS ( SELECT * FROM TN WHERE NOT ( SC ) )
       is True.

And SC is defined as (ISO/IEC 9075-2:2003 (E) SQL 2003 Part 2 -
SQL/Foundation, p. 567):

    UNIQUE ( SELECT UCL FROM TN)

where UCL is the unique column list and TN the table name.

The unique predicate is defined as follows (ISO/IEC 9075-2:2003 (E)
SQL 2003 Part 2 - SQL/Foundation, p. 422):

    2) If there are no two rows in T such that the value of each
       column in one row is non-null and is not distinct from the
       value of the corresponding column in the other row, then the
       result of the <unique predicate> is True; otherwise, the result
       of the <unique predicate> is False.

where T is the argument to UNIQUE (the table sub-query).

The definition of distinct is (ISO/IEC 9075-2:2003 (E) SQL 2003 Part 2
- SQL/Foundation, p. 29):

    3.1.6.8 distinct (of a pair of comparable values): Capable of
            being distinguished within a given context.  Informally,
            not equal, not both null. A null value and a non-null
            value are distinct.

    For two non-null values, the following rules apply:
    --  Two values of predefined type or reference type are distinct
        if and only if they are not equal. 

(I do not bother to quote the definition of equal, since I hope it is
understood by most programmers)


2. Conclusion
==================================================

When you are finished parsing the negations in the definition of the
unique predicate the you will find that the standard allows as many
NULL's as you wish under an unique constraint. *BUT*: you can't have a
unique constraint on columns which do not have the NOT NULL constraint
unless optional feature T591 is implemented. Thus, Derby is perfectly
compliant with SQL 2003 Mandatory.

Indices are *NOT* a part of the SQL standard, so no one can claim that
Derby's implementation of unique indices is wrong or right.

One can, however, conclude that Derby's implementation of unique
indices is not conformant with the SQL unique predicate.

Personally i think that it is unfortunate that Derby's unique indices
are not compliant with the SQL 2003 standard unique predicate.


Appendix A: A note on implementation
================================================== 

For those wondering how unique indices with multiple null values may
be implemented, it can be done pretty simple: The columns with null
values are not part of the index. This will if course affect the
execution plan.

Example:

CREATE TABLE t (i INTEGER, a INTEGER NOT NULL, b INTEGER);
CREATE UNIQUE INDEX idx1 ON t(i);
CREATE UNIQUE INDEX idx2 ON t(a, b);

SELECT i FROM t WHERE i=1;       -- Use index idx1
SELECT i FROM t WHERE i IS NULL; -- Do a table scan
SELECT a FROM t WHERE a=5;       -- Do a table scan
SELECT a FROM t WHERE a=5 AND b IS NOT NULL;
                                 -- Use index idx2

There is of course are other ways of implementing unique indices with
multiple null values.
-- 
Bernt Marius Johnsen, Database Technology Group, 
Sun Microsystems, Trondheim, Norway