If we look at the list of data types on SQL Server, there are VARCHAR and NVARCHAR which are commonly used to store text/strings. So what's the difference between them besides the N prefix?
The main difference is that the NVARCHAR data type can contain Unicode characters such as Arabic, Korean, Japanese, and the like. As in the example below.
The VARCHAR result is displaying question marks (?) because it doesn't support Unicode Furthermore
| VARCHAR[(n)] | NVARCHAR[(n)] |
Basic Definition | a variable-length character string, to store non-Unicode characters | Unicode variable-length character string, to store characters that are Unicode but can also store non-Unicode data. |
Stored Data as | 8-bits of plain data | UTF-16 |
Number of Bytes needed for each character | 1 byte per character | 2 bytes per Unicode/Non-Unicode character. |
Range options for parameter n | The value of n can be from 1 - 8000. Maximum storage of 8000 non-Unicode characters. | The value of n can be from 1 - 4000. Maximum storage of 4000 Unicode/non-Unicode characters. |
If n is not specified in the declaration | will be considered 1 with a length of 1. | will be considered 1 with a length of 2. |
If n is not specified when using the CAST/CONVERT function | It depends on the version of SQL Server used in some it will be considered 30 with a length of 30. But I'm using MSSQL14.SQLEXPRESS so 40 with a size of 40. | It depends on the version of SQL Server used in some it will be considered 30 with a length of 60. But I am using MSSQL14.SQLEXPRESS so 40 with a size of 80. |
Which one to use | If the stored data does not contain Unicode. | If the stored data contains Unicode. |
Storage Size | Takes the number of bytes equal to the number of Characters entered plus two extra bytes to determine the offset. | Takes the number of bytes equal to double the number of Characters entered plus two extra bytes to determine the offset. |
When we want to assign a Unicode value to the NVARCHAR data type, we need to add the letter N in front of the single quote ('). Because otherwise Unicode will not be read.
The size difference of VARCHAR and NVARCHAR for the same number of characters:
Difference if length is not defined at declaration:
Difference if length is not defined while CAST/CONVERT:
0 Comments