Why can't I put a constraint on nvarchar(max)?

Sql ServerSql Server-2005

Sql Server Problem Overview


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?

Sql Server Solutions


Solution 1 - Sql Server

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.

Solution 2 - Sql Server

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.

Solution 3 - Sql Server

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElyaView Question on Stackoverflow
Solution 1 - Sql ServermmxView Answer on Stackoverflow
Solution 2 - Sql ServertvanfossonView Answer on Stackoverflow
Solution 3 - Sql ServerTommy CarlierView Answer on Stackoverflow