Friday, 2 March 2018

Difference between char,nchar,varchar and nvarchar in sql server

Char Data Type - It can store alphanumeric characters(special characters also). But size of char datatype is fixed. Each character takes 1 bytes in memory. If storing 'Ashish1@!' whose length is 9 but it occupied memory of 20 bytes,rest of 11 bytes is waistage of memory.Maximum size of char is 8000 characters.It store non-unicode values.Char datatype is suitable when we know exact size of data to stored in database. Exp- Gender char(1) for M/F


declare @ch char(20)

set @ch ='Ashish1@!'

select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength




nchar DataType - It can store alphanumeric characters(special characters also). But size of nchar datatype is fixed. Each character takes 2 bytes in memory. If storing 'Ashish1@!' whose length is 9 but it occupied memory of 40 bytes. Maximum size of nchar is 4000 characters.It store unicode & non unicode values.nchar datatype is suitable when we know exact size of data to stored in database.

declare @ch nchar(20)

set @ch ='Ashish1@!'


select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength






Varchar DataType - It can store alphanumeric characters(special characters also). But size of Varchar datatype is not fixed. Each character takes 1 bytes in memory. If storing 'Ashish1@!' whose length is 9 so it occupied memory of 9 bytes only, rest of 11 bytes of memory is free.Maximum size of Varchar is 8000 characters.It store non-unicode values.Varchar datatype is suitable when we do not know exact size of data to stored in database.

declare @ch Varchar(20)

set @ch ='Ashish1@!'


select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength





nVarchar DataType - It can store alphanumeric characters(special characters also). But size of nVarchar datatype is not fixed. Each character takes 2 bytes in memory. If storing 'Ashish1@!' whose length is 9 so it occupied memory of 9*2 = 18 bytes only, rest of 22 bytes of memory is free.Maximum size of nVarchar is 4000 characters.It store unicode & non unicode values.nVarchar datatype is suitable when we do not know exact size of data to stored in database.

declare @ch nVarchar(20)

set @ch ='Ashish1@!'


select @ch as Name,DATALENGTH(@ch) as OccupiedLength,LEN(@ch) as CharacterLength






1 comment: