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
- DECLARE @string CHAR(20)
- SET @string = 'Robin'
- 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
- DECLARE @string VARCHAR(20)
- SET @string = 'Robin'
- 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
- DECLARE @string NCHAR(20)
- SET @string = 'Robin'
- 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
- DECLARE @string NVARCHAR(20)
- SET @string = 'Robin'
- 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