Difference between char and varchar in SQL server
Almost everyone knows the difference between CHAR and VARCHAR data types. I will tell you about one more difference which I saw recently.
CHAR is a data type with a fixed length. Suppose you declare a variable or column of CHAR (10) data type. It will take 10 bytes respectively, even if you store 1 character or 10 characters in the variable or column. We can keep maxim 10 characters n the column. The maximum number of characters is 255. It is 50% faster than VARCHAR and uses static memory allocation.
VARCHAR is a variable-length data type. If you have a variable/column of VARCHAR(10), it will take the number of bytes equal to the number of characters stored in the variable/column. In this variable/column, if you are storing only one character, it will take only one byte, and if we are holding 10 characters, it will take 10 bytes. In the example, we declared the variable/column as VARCHAR (10), and we can store max 10 characters in the column. The maximum data type can hold is
- Pre-MySQL 5.0.3: 255 characters
- Post-MySQL 5.0.3: 65 535 characters shared for the row.
It is slower than CHAR and uses dynamic memory allocation.
Here is an example:
DECLARE @CharName Char(20) = 'Maria',
@VarCharName VarChar(20) = 'Maria'
SELECT DATALENGTH(@CharName) CharSpaceUsed,
I hope it helps.