views:

650

answers:

4

Why can't I create a constraint on an nvarchar(max) column? SQL Server will not allow me to put a unique constraint on it. But, it allows me to create a unique constraint on an nvarchar(100) column.

Both of these columns are NOT NULL. Is there any reason I can't add a constraint to the nvarchar(max) column?

+7  A: 

Because MAX is really big (231-1 bytes) and could lead to a server meltdown if the server had to check for uniqueness on multi-megabyte-sized entries.

From the documentation on Create Index, I would assume this holds true for unique constraints as well.

The maximum allowable size of the combined index values is 900 bytes.

EDIT: If you really needed uniqueness, you could, potentially approximate it by computing a hash of the data and storing that in a unique index. Even a large hash would be small enough to fit in an indexable column. You'd have to figure out how to handle collisions -- perhaps manually check on collisions and pad the data (changing the hash) if an errant collision is found.

tvanfosson
To that end, is there some set maximum value that the index can be, or is it just 'not MAX'?
Matthew Scharley
I think the maximum length of `nvarchar` and `varchar` is somewhere in the 8000-range, unless you use MAX.
Thorarin
The maximum total size of all the key columns of an index is 900 bytes.http://msdn.microsoft.com/en-us/library/ms191241.aspx
Tommy Carlier
Since nvarchar is using two bytes to code single character, nvarchar(450) is max value that can be an index.
RaYell
+2  A: 

A unique constraint is actually an index, and nvarchar(max) cannot be used as a key in an index.

Tommy Carlier
+10  A: 

nvarchar(max) is really a different data type from nvarchar(integer-length). It's characteristics are more like the deprecated text data type.

If nvarchar(max) value becomes too large, like text, it will be stored outside the row (a row is constrained to 8000 bytes maximum) and a pointer to it is stored in the row itself. You cannot efficiently index such a large field and the fact that data can be stored somewhere else further complicates searching and scanning the index.
A unique constraint requires an index to be enforced and as a result, SQL Server designers decided to disallow creating a unique constraint on it.

Mehrdad Afshari
+1 Nicely explained!
Andrew Hare
Of course, they could have used a version of CRC or MD5 to make the constraint cheap to check with excessively high probability. In any case; they didn't...
Eamon Nerbonne
A: 

Thank you!! I understand!!

You can mark one of the above answers as the accepted answer and/or vote up any useful posts; this helps future readers and rewards those that spend the effort of answering ;-).
Eamon Nerbonne