Sunday, 11 September 2016

Differences among VARCHAR,CHAR,NVARCHAR,NCHAR in SQL Server?

1.       Why do we need CHAR when VARCHAR is there with flexible size?

CHAR variable gets the memory allocated according to the size given immediately without waiting for how much gets used. CHAR gets the memory space at a single block hence it’s easy to access.
Whereas VARCHAR gets the memory depending on much getting used and won’t get memory in a single block, hence not as faster as char.

CHAR and VARCHAR both take 1 byte for each character

In the below examples LEN() function gives the length of the string and DATALENGTH() function gives the size of the space allocated.

Examples:

CHAR Datatype




VARCHAR Datatype

Opt for CHAR datatype when have the clarity that column is going to have the fixed length.
As already explained above it gives the better performance due to single block allocation of the memory

2.       Why CHAR instead of NVARCHAR?
Differences between NCHAR and NVARCHAR remain as diff between CHAR and VARCHAR.
Added things are NCHAR and NVARCHAR support Unicode character support.
Both NCHAR and NVARCHAR take 2 bytes for each character.

Examples:

NCHAR Datatype

NVARCHAR Datatype

From the above example it’s evident that NVARCHAR takes 2 bytes for each character.

3.       What are UNICODE and NONUNICODE characters?

In this present world no one wants to limit their business to a particular language or region.
So it’s unavoidable to provide different language support for the database.
Unicode characters take more than one byte to store data in database. To support languages like FRENCH,ITALY we need Unicode characters

Example:
              
VARCHAR Doesn't support unicode
  In the above example I tried to save a Telugu language word in a string @Name,but as                        @NAME is a VARCHAR datatype and doesn’t support unicode character.It is not stored properly in database.

Unicode support for @NAME By declaring it as NVARCHAR

NVARCHAR Unicode support



In the above example Telugu language string is stored properly in the database.