SQL Server and the limit of primary key sizes: warning shown when you get close or over to the limit

Posted: (EET/GMT+2)

 

A quick reminder on the limits of primary keys in tables on SQL Server: a clustered key has the maximum size of 900 bytes, i.e. around 450 characters of NVARCHAR data.

Assume you have the following table:

CREATE TABLE MyTable (
            [SomeId] [int] NOT NULL,
            [SomeString] [nvarchar](500) NOT NULL
PRIMARY KEY CLUSTERED 
(
            [SomeId] ASC,
            [SomeString] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

If you run this DDL statement to create the table, you will get the following warning:

Warning! The maximum key length is 900 bytes. The index 'PK__MyTable__1234567890' has
maximum length of 1004 bytes. For some combination of large values, the insert/update
operation will fail.

So, it might work for small amounts of data, but not for very long strings.

Something to keep in mind while designing your tables!