Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a unique constraint column have 2 or more null values? (oracle)

Tags:

Is it possible to have 2 or more null values in unique constraint column?

like image 711
Shubham Anand Avatar asked Oct 13 '16 17:10

Shubham Anand


People also ask

Can unique constraint have multiple NULL values in Oracle?

A null is never equal (nor not equal) to any other null, hence, a unique constraint on a single attribute will allow as many null rows as you can stuff in there.

Can unique column have multiple NULL values?

Remember, you cannot add more than one null value to a unique key column since the second null value will be the duplicate of the first one – and duplicates are not allowed.

Can there be multiple NULL values in column which have unique constraint set?

The correct answer is no: The unique constraint doesn't let you add multiple records that contain a value of NULL. (See also, "Unique Constraints with Multiple NULLs," March 2008).

How many NULL values are allowed in unique constraint?

Another difference is that the UNIQUE constraint allows for one NULL value, but the PRIMARY KEY does not allow NULL values.


1 Answers

Easy to check: (The answer is YES)

create table t1 (col1 number unique);  Table T1 created.  insert into t1 values (1);  1 row inserted.  insert into t1 values (null);  1 row inserted.  insert into t1 values (null);  1 row inserted.  select rownum, col1 from t1;      ROWNUM       COL1 ---------- ----------          1          1          2                     3             3 rows selected. 

Edit: While what I show above is the answer when only one column is involved in a unique constraint, one can also have composite unique keys (constraints defined at the table level, rather than column level - involving two or more columns). In that case, if say the unique key is on (col1, col2, col3), then (1, 1, 0) and (1, 1, 3) are not duplicates, because they aren't identical in every position. In this case, (1, 1, null) is allowed, but only once. The correct "generalization" of null "value" in a column, however, is for ALL values in ALL THREE columns to be null. In that regard, rows with "null values" in the unique key columns are still allowed any number of times.

That is: While (1, 1, null) is allowed, but not more than once, a row with values (null, null, null) in the three columns that make up the unique key are allowed any number of times - just like in the single-column case.

like image 161
mathguy Avatar answered Oct 29 '22 00:10

mathguy