Why is the default size of nvarchar is 255 (MSSQL Server)?

sql, sql-server, t-sql, types

Solution

The documentation is quite clear:

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30.

ALWAYS use a length specification for these variables.

As for your second question. The types `varchar` and `nvarchar` encode the length of the value for each value. I am not sure if SQL Server uses 1 byte for lengths up to 255 and then 2 bytes for lengths up to 4000/8000. The `max` does use 4-bytes. (And all of them can now spill over to additional pages.) In general, for variable character strings, you should use a value that is amply large for whatever you want to include, so you don't have to change the length using `alter table`. Only the necessary storage for a particular value is used, so a slightly longer declaration does not affect performance.

Note that for `char` and `nchar`, you want the shortest possible length because the column will actually occupy that storage space.

Problem

Why is the default size of `nvarchar` is 255 (`MSSQL Server`)? I mean why not 256? And should I use `nvarchar(63)` instead of `nvarchar(64)` and so on ... 127 instead 128? I tried to Google this question and I didn't find any comprehensive answer. Edited: About default size: It is just my assumption. Hibernate and EclipseLink (java persistence frameworks) convert String to nvarchar(255) so I thought this is so kind of standard.

Original source