Saturday, 26 September 2015

Difference Between Char and Varchar in SQL Server

Below list is major difference between Char[n] and varchar[n] Datatype in Sql Server;

Type
char[n]
Varchar[n]
Storage Type
Char is fixed length of datatype.
 If you declare variable with 20 character length. Like Char(20), 
it takes 20 bytes regardless storing 1 or 20 character.
varchar is fixed length of datatype. If you declare variable with 20 character length. Like varchhar(20), it takes number of bytes as defined.
Storage Example
DECLARE @Name Char(20) = 'Bob'
 SELECT DATALENGTH(@Name) as Result


Result
-----------
20

DECLARE @Name VarChar(20) = 'Bob'
 SELECT DATALENGTH(@Name) as Result

Result
-----------
3
Performance
If your content is fixed size than Char datatype has good to use.
It is performing better than char if variable datatype.
Which should Use
 Data can have Unicode characters.
Data doesn’t have any Unicode characters.



No comments:

Post a Comment