0

How do you define unique constraint in terms of nulls ? Is there any standard followed by all the databases to allow nulls in unique column.

Vivek
  • 11,938
  • 19
  • 92
  • 127

3 Answers3

1

Quoted from a blog, here is the amount of NULL values allowed in a column with a UNIQUE constraint, in a few DBMS :

What other DBMSs do

Trudy Pelzer and I wrote this on page 260 of our book, SQL Performance Tuning: DBMS Maximum number of NULLs when there is a UNIQUE constraint

IBM (DB2) One

Informix One

Ingres Zero

InterBase Zero

Microsoft (SQL Server) One

MySQL Many [although the BDB storage engine was an exception]

Oracle Many

Sybase One

Trying the following code in Sql Server (2012 Express, at least) fails, as expected :

DECLARE @T TABLE
(
    value int unique
)
INSERT INTO @T VALUES(1)
INSERT INTO @T VALUES(2)
INSERT INTO @T VALUES(NULL)
INSERT INTO @T VALUES(NULL)

The article mentions that the correct rule about handling null values in a column with a unique constraint should be that the value of the unique column of any two rows, if both are not NULL, should not be equal.

In other words, non null values must be unique, and multiple null values are allowed.

But not all DBMS seems to apply that rule, so it's better to confirm it with a simple test.

David Khuu
  • 937
  • 3
  • 10
  • 21
0

"...a UNIQUE column can have multiple NULLs in a row unless you explicitly add a NOT NULL constraint to each column."

Joe Celko's "SQL for Smarties", 2nd edition, Page 16.

For some fun with NULL-s, try these:

SELECT 1 = NULL (returns NULL)

SELECT 1 IS NULL (returns FALSE)

András Aszódi
  • 8,948
  • 5
  • 48
  • 51
0

It depends on the database engine. MySQL allow null duplicates but SQL Server doesn't.

You can try this on SQLFiddle. MySQL return an exception for the user 'ddd' while MySQL return an exception for the user 'ccc'

CREATE TABLE users (
  username varchar(20) NOT NULL,
  id int unique
);

insert into users values ('aaa', null);
insert into users values ('bbb', 1);
insert into users values ('ccc', null);
insert into users values ('ddd', 1);
JCalcines
  • 1,236
  • 12
  • 25