In Oracle UNIQUE constraint allows more than one NULL values to be inserted. ORACLE considers one NULL value is not equal to another NULL value.
col1 VARCHAR2(2),
col2 VARCHAR2(2)
);
Table created
ALTER TABLE test1
ADD CONSTRAINT test_unique UNIQUE (col1);
Table altered
INSERT INTO test1
VALUES ('a', 'a');
1 row inserted
INSERT INTO test1
VALUES ('a', 'a');
ORA-00001: unique constraint (TEST_UNIQUE) violated
INSERT INTO test1
VALUES (NULL, 'a');
1 row inserted
INSERT INTO test1
VALUES (NULL, 'a');
1 row inserted
DROP CONSTRAINT test_unique;
TRUNCATE TABLE table1;
ADD CONSTRAINT unique2 UNIQUE (col1,col2);
Insert null values to both columns.
INSERT INTO test1
VALUES (NULL, NULL);
1 row inserted
INSERT INTO test1
VALUES (NULL, NULL);
1 row inserted
But the results changes when we have only one NULL value for this composite UNIQUE constraint.
VALUES (NULL, 'a');
1 row inserted
INSERT INTO test1
VALUES (NULL, 'a');
ORA-00001: unique constraint (UNIQUE2) violated
I do not understand why composite unique constraint violated on last two inserts.
ReplyDeletecan you please explain?