简体   繁体   中英

Workaround maximum key length for a nonclustered index in SQL Server

Is there a way to increase the limit for a nonclustered index which is 1700 bytes in SQL Server? When I build my database I get this warning:

Warning. The maximum key length for a nonclustered index is 1700 bytes. The index 'CS_UK' has maximum length of 8000 bytes, For some combination of large values. the insert/update operation will fail.

Or do I have to change the structure of my indexes?

Even if it were possible, you should consider changing your index structure. That being said, from the blog of the engineering team :

SQL Server 2016 and Azure SQL Database have increased the maximum size for index keys with nonclustered indexes. The new maximum key size for nonclustered indexes is 1700 bytes. The maximum key size for clustered indexes remains 900 bytes.

At the end of the article they add:

For memory-optimized tables: the maximum index key size for nonclustered indexes is 2500 bytes; there is no strict limit on index key size for hash indexes.

So it might be possible.

A workaround is to use include for the columns which are too big when creating the index.

CREATE NONCLUSTERED INDEX IX_IndexSizeTest_Test3 
ON IndexSizeTest (EMPName,EmpPhoneNumber,EmpPostCode) INCLUDE (EmpAddress) 

When EmpAdress in this example would be a very huge column we can add it to the index with INCLUDE(EmpAddress) because then it won't be counted when it comes to the index limitation. Here are more details about it.

OP didn't specify the details that led to the warning, but I had same warning when indexing on a computed column that itself was derived from a nvarchar(max) column.

When creating the computed column, restrict its length by CASTing. Credit to this post for the idea. This reduced my computed column length from 4000 to 100 and let me create the index without any warnings.

ALTER TABLE table_name
ADD v_new_computed_column
AS CAST(JSON_VALUE(json_column,'$.some_key') AS NVARCHAR(100) ) ;

For reference, the MS docs sanctions this JSON computed value index, but didn't address this edge case.

You are getting the warning because the column you are trying to index is very large. For us, we realized we didn't need that large a column to index, nor would it be good performance. So, if you don't actually need that size, shrinking the column provides more structure and safety. I'm no longer worried about someone accidentally throwing too much in there, and failing the insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM