NCHAR Data Type

The NCHAR data type is a fixed-length Unicode character data type. It stores strings of a fixed size that are specified when the table is created. When you declare a column as NCHAR(n), each row in that column will always occupy n bytes of storage, regardless of the actual length of the string stored.

Description

NCHAR(n) is used to store Unicode characters. Unicode uses two bytes per character, unlike single-byte character sets. This means that NCHAR(n) stores a maximum of n characters, and the storage size for the column will be 2 * n bytes.

If a string inserted into an NCHAR(n) column is shorter than n characters, the string will be padded with spaces on the right to reach the specified length. If the string is longer than n characters, SQL Server will return an error.

Syntax

NCHAR ( n )

Where n is the length of the string in bytes. n must be a value from 1 to 4000.

When to Use NCHAR

For variable-length Unicode strings, consider using NVARCHAR.

Note: Using NCHAR(n) when the actual data length varies significantly can lead to wasted storage space due to padding. NVARCHAR(n) is often a more efficient choice for variable-length data.

Example Usage

The following example creates a table named Languages with an NCHAR(10) column for storing language codes.

CREATE TABLE Languages (
    LanguageID INT PRIMARY KEY,
    LanguageCode NCHAR(10)
);

INSERT INTO Languages (LanguageID, LanguageCode) VALUES (1, 'EN');
INSERT INTO Languages (LanguageID, LanguageCode) VALUES (2, 'FR');
INSERT INTO Languages (LanguageID, LanguageCode) VALUES (3, 'DE');
INSERT INTO Languages (LanguageID, LanguageCode) VALUES (4, 'ES '); -- Padded with spaces

Querying NCHAR Data

When you query NCHAR data, trailing spaces are typically preserved. However, comparison operations might ignore them depending on the collation settings.

SELECT * FROM Languages WHERE LanguageCode = 'EN';
SELECT * FROM Languages WHERE LanguageCode = 'EN          '; -- Will also match if padding is exact

Comparison with CHAR

CHAR is a fixed-length data type that stores non-Unicode characters. NCHAR stores Unicode characters.

If your application needs to support international characters, use NCHAR or NVARCHAR. For only standard ASCII or extended ASCII characters, CHAR or VARCHAR might be sufficient.

Storage Requirements

Data Type Storage Size
NCHAR(n) 2 * n bytes
Tip: The maximum length for NCHAR and NVARCHAR in SQL Server is 4000 characters. For larger Unicode strings, consider using MAX (e.g., NVARCHAR(MAX)).