What is difference between VARCHAR and NVARCHAR in SQL server - SQL Server / T-SQL Tutorial Part 32

Varchar is variable length character data type which is used to store Non-Unicode data format. You can think of Non-Unicode as English characters.

NVarchar is also variable length character data type which is used to store UniCode data format. For Unicode data formats you can think of alphabets of Chinese, Japanese, Korean and Arabic language.

Varchar can stored 'English' characters and it take one byte to store each character. Nvarchar can store English and other languages characters. NVarchar take two bytes to store each character.

 Let's create two variables and check the space used by each variable.

Declare @Variable1 VARCHAR(20)
Declare @Variable2 NVARCHAR(20)

SET @Variable1='TechBrothersIT'
SET @Variable2='TechBrothersIT'

Select datalength(@Variable1) as VarLength1, datalength(@Variable2) as VarLength2

What is the difference between VARCHAR and NVARCHAR - SQL Server Tutorial


As we have declare @Variable2 as NVarchar, it took twice the space as compared to @Variable1 which is Varchar to store the characters.


Let's create a table with Varchar and NVarchar Data type columns and insert few records.

Create table dbo.VarcharVsNvarchar( VarcharName Varchar(50),NVarcharName NVARCHAR(50))
insert into dbo.VarcharVsNvarchar  Values
('عامر','عامر'),
('عامر',N'عامر'),
('TechBrothersIT',N'TechBrothersIT')

Select * from dbo.VarcharVsNvarchar
go
Select DataLength(VarcharName) AS CHARNameLength,DataLength(NVarcharName) AS VarNameLength 
From dbo.VarcharVsNvarchar

Varchar VS Nvarchar in SQL Server - TSQL Tutorial


Our first Select query returned us the data. Noticed that we have some garbage data ????. Even we have defined the data type of column NVarchar, it inserted the garbage. To insert Unicode data in Nvarchar type column, we need to Use N with data as you can see in second insert ( ('عامر',N'عامر')).

4 comments: