What is the difference Between CHAR and NCHAR data types?
CHAR
- CHAR data type is used to store non-Unicode string data of fixed-length.
- Stores data at 1 byte per character.
- Supports up to 8000 characters.
Syntaxโฉchar(n)
n specify the string length that ranges from 1 to 8000. Default value for n is 1.
NCHAR
- NCHAR data type is used to store Unicode string data of fixed-length.
- It stores data at 2 byte per character.
- It supports up to 4000 characters.
Syntaxโฉnchar(n)
n specify the string length that ranges from 1 to 4000. Default value for n is 1.
Lets demonstrate the difference between CHAR vs NCHAR
Data Storage Vs Length
- CHAR
In following T-SQL, declared a variable @str that is of datatype char of size 15.
DECLARE @Str CHAR(15)โฉSET @Str = 'Microsoft'โฉSELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength ,โฉLEN(@Str) AS StrText_length
As char has fixed-length and takes 1 bytes per character to store the data so it takes 15 bytes to store value ‘microsoft’ , even though the length of value ‘microsoft’ is 9 .
So the data storage length of characters will be the fixed-length of variable @str* 1 bytes (15 *1) =15.
- NCHAR
In following T-SQL, declared a variable @str that is of datatype nchar of size 15.
DECLARE @Str NCHAR(15)โฉSET @Str = 'Microsoft'โฉSELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength ,โฉLEN(@Str) AS StrText_length
As nchar has fixed-length and takes 2 bytes per character to store the data so it takes 30 bytes to store @str value ‘microsoft’ , even though the length of value ‘microsoft’ is 9 .
So the data storage length of characters will be the fixed-length of variable @str * 2 bytes (15 *2) =30.
Using CHAR and NCHAR to store Unicode Data
- CHAR
Char can not store unicode data, here we try to store Hindi language text to @str variable of type char.
Note: Always make sure that you prefix Unicode string literals with an N prefix.
DECLARE @Str CHAR(15)โฉSET @Str = N'เคฎเคพเคเคเฅเคฐเฅเคธเฅเคซเฅเค'โฉSELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength ,โฉLEN(@Str) AS StrText_length
As you can see, it does not support unicode characters /multilingual data.
- NCHAR
NCHAR can store unicode data, again we try to store hindi language text to @str variable of type nchar.
Note: Always make sure that you prefix Unicode string literals with an N prefix.
DECLARE @Str NCHAR(15)โฉSET @Str = N'เคฎเคพเคเคเฅเคฐเฅเคธเฅเคซเฅเค'โฉSELECT @Str AS Strtext, DATALENGTH(@Str) AS StrText_OccupiedLength ,โฉLEN(@Str) AS StrText_length
You can see, it returns the unicode data that can be seen in the first column of result set.
Also Read..
SQL Server VARCHAR VS NVARCHAR
How to get the detailed information of all datatypes in SQL Server ?
975 total views, 4 views today