In SQL Server, VARCHAR and NVARCHAR are used to store text data. The main difference is how they store characters and support languages.
1. What is VARCHAR?
VARCHAR stores non-Unicode characters. It is mainly used for English or single-language data.
- Uses 1 byte per character
- Stores English text
- Saves storage space
Name VARCHAR(50)
2. What is NVARCHAR?
NVARCHAR stores Unicode characters. It supports multiple languages.
- Uses 2 bytes per character
- Supports all languages
- Used for international applications
Name NVARCHAR(50)
3. Key Differences
| Feature | VARCHAR | NVARCHAR |
|---|---|---|
| Storage | 1 byte | 2 bytes |
| Language | Single | Multiple |
4. Insert Example
INSERT INTO Students (Name)
VALUES ('Ravi');
INSERT INTO Students (Name)
VALUES (N'रवि');
5. GET LENGTH Example
Use LEN() to get character count and DATALENGTH() to get storage size.
DECLARE @v VARCHAR(10) = 'Ravi'; DECLARE @n NVARCHAR(10) = N'Ravi'; SELECT LEN(@v) AS Varchar_Length, DATALENGTH(@v) AS Varchar_Bytes, LEN(@n) AS NVarchar_Length, DATALENGTH(@n) AS NVarchar_Bytes;
Result:
| Type | LEN() | DATALENGTH() |
|---|---|---|
| VARCHAR | 4 | 4 bytes |
| NVARCHAR | 4 | 8 bytes |
Conclusion
VARCHAR saves space, while NVARCHAR supports multiple languages. Use LEN() for length and DATALENGTH() for actual storage size.
Your learning journey continues 🚀
Tags
MS SQL Server