Tag Archives: VARCHAR

Difference Between Sql Server VARCHAR and VARCHAR(MAX) Data Type

Ideally, it is better to compare Text and Varchar(MAX) data types, as in Sql Server 2005 Varchar(MAX) data type was introduced as an alternate for Text data type. Varchar(Max) data type provides multiple advantages over Text data type.

Like many initially when Varchar(MAX) datatype was introduced in Sql Server 2005, I too was not clear about the difference between Varchar and Varchar(Max) and which one to use when. Hope the differences listed in the below table clarifies these queries.

Varchar[(n)] Varchar(Max)
Basic Definition Non-Unicode Variable Length character data type.
Example:

DECLARE @Name VARCHAR(50)
         = 'BASAVARAJ'
SELECT @Name
Non-Unicode large Variable Length character data type.
Example:

DECLARE @Name VARCHAR(Max)
         = 'BASAVARAJ'
SELECT @Name
 Storage Capacity It can store maximum 8000 Non-Unicode characters (i.e. maximum storage capacity is 8000 bytes of storage). Optional Parameter n value can be from 1 to 8000. It can store maximum of 2 147 483 647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).
Index? You can create index on Varchar column data type.
Example:

CREATE TABLE dbo.Employee
(id INT identity(1,1)
   PRIMARY KEY,
 Name VARCHAR(50))
GO
CREATE INDEX IX_EmployeeName 
 ON dbo.Employee(Name)
GO
Index can’t be created on a Varchar(Max) data type columns.
Example:

CREATE TABLE dbo.Employee
(id INT identity(1,1)
   PRIMARY KEY,
 Name VARCHAR(Max))
GO
CREATE INDEX IX_EmployeeName
 ON dbo.Employee(Name)
GO 

Error Message:
Msg 1919, Level 16, State 1, Line 1 Column ‘Name’ in table ‘dbo.Employee’ is of a type that is invalid for use as a key column in an index.

How data is stored Physically? It uses the normal data pages to store the data i.e. it stores the value ‘in a row’. Sql server will try to store the value ‘in a row’ but if it could not then it will store the value ‘out of row’. i.e. It uses the normal data pages until the content actually fills 8k of data.When overflow happens, data is stored as old TEXT Data Type and a pointer is replacing the old content.
No. of Bytes required for each character It takes 1 byte per character
Example:

DECLARE @Name VARCHAR(50)
         ='BASAVARAJ'
SELECT @Name Name,
 DATALENGTH(@Name) Length

Result:
Name Length
BASAVARAJ 9

It takes 1 byte per character
Example:

DECLARE @Name VARCHAR(MAX)
         ='BASAVARAJ'
SELECT @Name Name, 
 DATALENGTH(@Name) Length

Result:
Name Length
BASAVARAJ 9

Which one to use? If we know that data to be stored in the column or variable is less than or equal to 8000 characters, then we can use this data type.For example First Name, Last Name etc, columns value can’t cross the max 8000 characters limit, in such scenario’s it is better to use this data type. If we know that the data to be stored in the column or variable can cross a 8KB Data page, then we can use this data type.
Performance There is not much performance difference between Varchar[(n)] and Varchar(Max). Varchar[(n)] provides better performance results compared to Varchar(Max). If we know that data to be stored in the column or variable is less than or equal to 8000 characters, then using this Varchar[(n)]  data type provides better performance compared to Varchar(Max).Example: When I ran the below script by changing the variable @FirstName type to Varchar(Max) then for 1 million assignments it is consistently taking double time than when we used data type as Varchar(50) for variable @ FirstName.

DECLARE @FirstName VARCHAR(50), @COUNT INT=0, 
        @StartTime DATETIME = GETDATE()
WHILE(@COUNT < 1000000)
BEGIN
   SELECT @FirstName = 'BASAVARAJ', @COUNT = @COUNT +1
END
SELECT DATEDIFF(ms,@StartTime,GETDATE()) 'Time Taken in ms'
GO 6

Note: Here GO 6 statement executes the statements above it 6 times.

[ALSO READ] You may like to read below other popular articles on differences

1. Varchar vs NVarchar
2. Varchar vs Varchar(MAX)
3. Char vs Varchar
4. Text vs Varchar(Max)
5. Union vs Union All
6. DateTime vs DateTime2
7. SET QUOTED_IDENTIFIER ON vs SET QUOTED_IDENTIFIER OFF
8. Stored Procedure vs User Defined Function
9. Primary Key vs Unique Key
10. RAISERROR vs THROW
11. Temporary Table vs Table Variable
12. Len() vs Datalength()
13. Sequence vs Identity
14. DATEDIFF vs DATEDIFF_BIG

Difference Between Sql Server VARCHAR and NVARCHAR Data Type

Below table lists out the major difference between the VARCHAR and NVARCHAR Data Type in Sql Server:

Varchar[(n)] NVarchar[(n)]
Basic Definition Non-Unicode Variable Length character data type.
Example:
DECLARE @FirstName AS VARCHAR(50) =‘BASAVARAJ’
SELECT @FirstName
UNicode Variable Length character data type. It can store both non-Unicode and Unicode (i.e. Japanese, Korean etc) characters.
Example:
DECLARE @FirstName AS NVARCHAR(50)= ‘BASAVARAJ’
SELECT @FirstName
No. of Bytes required for each character It takes 1 byte per character

Example:
DECLARE
@FirstName AS VARCHAR(50) = ‘BASAVARAJ’
SELECT @FirstName AS FirstName,
DATALENGTH(@FirstName) AS
Length

Result:
FirstName Length
BASAVARAJ 9

It takes 2 bytes per Unicode/Non-Unicode character.
Example:
DECLARE
@FirstName AS NVARCHAR(50)= ‘BASAVARAJ’
SELECT @FirstName AS FirstName,
DATALENGTH(@FirstName) AS Length

Result:
FirstName Length
BASAVARAJ 18
Optional Parameter n range Optional Parameter n value can be from 1 to 8000.Can store maximum 8000 Non-Unicode characters. Optional Parameter n value can be from 1 to 4000.Can store maximum 4000 Unicode/Non-Unicode characters
If Optional Parameter n is not specified in the variable declaration or column definition If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.
Example:
DECLARE
@firstName VARCHAR = ‘BASAVARAJ’
SELECT
@firstName FirstName, DATALENGTH(@firstName) Length

Result:
FirstName Length
B 1
If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.
Example:
DECLARE @firstName NVARCHAR = ‘BASAVARAJ’
SELECT
@firstName FirstName, DATALENGTH(@firstName) Length

Result:
FirstName Length
B 2
If Optional Parameter n is not
specified in while using
CAST/ CONVERT functions
When this optional parameter n is not specified while using the CAST/CONVERT functions, then it is considered as 30.Example:
DECLARE @firstName VARCHAR(35) =
‘BASAVARAJ PRABHU BIRADAR INDIA ASIA’

SELECT CAST(@firstName AS VARCHAR) FirstName,
DATALENGTH
(CAST(@firstName AS VARCHAR)) Length

Result:

FirstName Length
BASAVARAJ PRABHU BIRADAR INDIA 30
When this optional parameter n is not specified while using the CAST CONVERT functions, then it is considered as 30.Example:
DECLARE @firstName NVARCHAR(35) =
‘BASAVARAJ PRABHU BIRADAR INDIA ASIA’

SELECT CAST(@firstName AS NVARCHAR) FirstName,
DATALENGTH
(CAST(@firstName AS NVARCHAR)) Length

Result:
FirstName Length
BASAVARAJ PRABHU BIRADAR INDIA 60
Which one to use? If we know that data to be stored in the column or variable doesn’t have any Unicode characters. If we know that the data to be stored in the column or variable can have Unicode characters.
Storage Size Takes no. of bytes equal to the no. of Characters entered plus two bytes extra for defining offset. Takes no. of bytes equal to twice the no. of Characters entered plus two bytes extra for defining offset.

As both of these are variable length datatypes, so irrespective of the length (i.e. optional parameter n value) defined in the variable declaration/column definition it will always take the no. of bytes required for the actual charcters stored. The value of n defines maximum no. of characters that can be stored.

[ALSO READ] You may like to read below other popular articles on differences

1. Varchar vs NVarchar
2. Varchar vs Varchar(MAX)
3. Char vs Varchar
4. Text vs Varchar(Max)
5. Union vs Union All
6. DateTime vs DateTime2
7. SET QUOTED_IDENTIFIER ON vs SET QUOTED_IDENTIFIER OFF
8. Stored Procedure vs User Defined Function
9. Primary Key vs Unique Key
10. RAISERROR vs THROW
11. Temporary Table vs Table Variable
12. Len() vs Datalength()
13. Sequence vs Identity
14. DATEDIFF vs DATEDIFF_BIG

Please correct me, if my understanding is wrong. Comments are always welcome

Difference between Sql Server Char and Varchar Data Type

Everyone knows about the basic difference between CHAR and VARCHAR data types. In this article apart from the basic difference, will discuss on one more interesting difference which I have observed recently.

CHAR Data Type is a Fixed Length Data Type. For example if you declare a variable/column of CHAR (10) data type, then it will always take 10 bytes irrespective of whether you are storing 1 character or 10 character in this variable or column. And in this example as we have declared this variable/column as CHAR(10), so we can store max 10 characters in this column.

On the other hand VARCHAR is a variable length Data Type. For example if you declare a variable/column of VARCHAR (10) data type, it will take the no. of bytes equal to the number of characters stored in this column. So, in this variable/column if you are storing only one character then it will take only one byte and if we are storing 10 characters then it will take 10 bytes. And in this example as we have declared this variable/column as VARCHAR (10), so we can store max 10 characters in this column.

Below example illustrates the basic difference explained above:

DECLARE @CharName Char(20) = 'Basavaraj',
  @VarCharName VarChar(20) = 'Basavaraj'
 SELECT DATALENGTH(@CharName) CharSpaceUsed,
  DATALENGTH(@VarCharName) VarCharSpaceUsed

Result:

CharSpaceUsed VarCharSpaceUsed
------------- ----------------
20            9
(1 row(s) affected)

Below is an interesting difference, which I have observed recently while writing some script.

Concatenation of CHAR variables:

DECLARE @FirstName Char(20) = 'Basavaraj',
  @LastName Char(20) = 'Biradar'

IF @FirstName + ' ' + @LastName = 'Basavaraj Biradar' 
 PRINT 'I was Expecting'
ELSE 
 PRINT 'Surprise to me ...'

SELECT  @FirstName + ' ' + @LastName AS Name,
 len(@FirstName + ' ' + @LastName) AS Length

Result:

Surprise to me …
Name                                      Length
—————————————– ———–
Basavaraj            Biradar              28
(1 row(s) affected)

Concatenation of VARCHAR variables:

DECLARE @FirstName VarChar(20) = 'Basavaraj',
 @LastName VarChar(20) = 'Biradar'

IF @FirstName + ' ' + @LastName = 'Basavaraj Biradar' 
 PRINT 'I was Expecting'
ELSE 
 PRINT 'Surprise to me ...'

SELECT  @FirstName + ' ' + @LastName AS Name,
 len(@FirstName + ' ' + @LastName) AS Length

Result:

I was Expecting
Name                                      Length
----------------------------------------- -----------
Basavaraj Biradar                         17
(1 row(s) affected)

So, it is clear from the above examples that during concatenation of CHAR data type variables, it includes space in-place of unused space in the result of concatenation.

[ALSO READ] You may like to read below other popular articles on differences
Varchar Vs NVarchar
Varchar Vs Varchar(MAX)
Union Vs Union All
DateTime Vs DateTime2
SET QUOTED_IDENTIFIER ON Vs OFF
Stored Procedure Vs User Defined Function
Primary Key Vs Unique Key
RAISERROR Vs THROW
Temporary Table Vs Table Variable
LEN() Vs DATALENGTH()
Sequence Vs Identity