SQL Server char and varchar Data Types


CHAR is a fixed-length, non-Unicode string data. n defines the string length and must be a non-fractional value from 1 through 8,000. The storage size is n bytes. The ISO synonym for char is character. The syntax is char [ ( n ) ].

VARCHAR is a variable-length, non-Unicode string data. n defines the string length and can be a non-fractional value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered + 2 bytes. The ISO synonyms for varchar are charvarying or charactervarying. The syntax is varchar [ ( n | max ) ]. The vertical pipe means “or”. As an example, you can use it this way: charchar(20) or varchar(MAX).

Objects that use char or varchar are assigned the default collation of the database, unless a specific collation is assigned using the COLLATE clause. The collation controls the code page that is used to store the character data.

One difference between CHAR/VARCHAR and NCHAR/NVARCHAR when specifying a literal string is that the NCHAR/NVARCHAR types should be preceded by the letter N. This tells the query processor to interpret the string as Unicode. If you don’t precede the literal string with the letter N, the code will usually still work.

Here below is some simple SQL Server code written in the Query window.

DECLARE @myChar3 as char(3)  -- fixed width
DECLARE @myChar20 as char(20)  -- fixed width
SET @myChar3 = 'hi'   -- adds spaces on right to fill to length
PRINT @myChar3
SET @myChar3 = 'hello world'  -- crops down to size
PRINT @myChar3
SET @myChar20 =  @myChar3 + 'lo!'  -- concatenate char and literals
PRINT @myChar20 + ' World'
PRINT RTRIM(@myChar20) + ' World' -- rtrim() trims spaces on the right

Here is a screenshot of the output.

Here is some more sql code and a screenshot of the output.

DECLARE @myVarChar3 as varchar(3)  -- variable width with 3 as the maximum
DECLARE @myVarChar20 as varchar(20)  -- variable width with 20 as the max
SET @myVarChar3 = 'hi'   -- NO spaces on right to fill to length
PRINT @myVarChar3
SET @myVarChar3 = 'hello world'  -- crops down to size
PRINT @myVarChar3
SET @myVarChar20 =  @myVarChar3 + 'lo!'  -- concatenate varchar and literals
PRINT @myVarChar20 + ' World'  -- not all 20 are used
PRINT RTRIM(@myVarChar20) + ' World' -- rtrim() not necessary

Here is a screenshot of the output.

Character Data Types

Name Type Maximum Characters Character Set
CHAR Fixed width 8000 ASCII
NCHAR Fixed width 4000 Unicode
VARCHAR Variable width 8000 ASCII
NVARCHAR Variable width 4000 Unicode
TEXT Variable width 2^31 – 1 ASCII
NTEXT Variable width 2^30 – 1 Unicode
VARCHAR(MAX) Variable width 2^31 – 1 ASCII
NVARCHAR(MAX) Variable width 2^30 – 1 Unicode

We have another post that discusses integer data types.