Friday, August 2, 2019

What is char, var, nchar , nvarchar

CHAR vs VARCHAR



CHAR:

  • It is a fixed length data type
  • Used to store non-Unicode characters
  • Occupiers 1 byte of space for each character

  1. DECLARE @string CHAR(20)  
  2. SET @string = 'Robin'  
  3. SELECT @string AS 'String', DATALENGTH(@string) AS 'Datalength' , LEN(@string) AS 'Len' 

VARCHAR:

  • It is a variable length data type
  • Used to store non-Unicode characters
  • Occupies 1 byte of space for each character
  1. DECLARE @string VARCHAR(20)  
  2. SET @string = 'Robin'  
  3. SELECT @string AS 'String', DATALENGTH(@string) AS 'Datalength' , LEN(@string) AS 'Len' 



NCHAR:

  • Is a fixed length data type
  • Used to store Unicode characters (for example the languages Arabic, German and so on)
  • Occupies 2 bytes of space for each character
  1. DECLARE @string NCHAR(20)  
  2. SET @string = 'Robin'  
  3. SELECT @string AS 'String', DATALENGTH(@string) AS 'Datalength' , LEN(@string) AS 'Len' 
 

NVARCHAR:

  • It is a variable-length data type
  • Used to store Unicode characters
  • Occupies 2 bytes of space for each character
  1. DECLARE @string NVARCHAR(20)  
  2. SET @string = 'Robin'  
  3. SELECT @string AS 'String', DATALENGTH(@string) AS 'Datalength' , LEN(@string) AS 'Len' 




When to use what?

If your column will store a fixed-length Unicode characters like French, Arabic and so on characters then go for NCHAR. If the data stored in a column is Unicode and can vary in length, then go for NVARCHAR. 
 
Querying to NCHAR or NVARCHAR is a bit slower then CHAR or VARCHAR. So don't go for NCHAR or NVARCHAR to store non-Unicode characters even though this data type supports that. 


No comments:

Post a Comment

How to use SQL pagination using LIMIT and OFFSET

  How to extract just a portion of a larger result set from a SQL SELECT. LIMIT n is an alternative syntax to the FETCH FIRST n ROWS ONLY. T...