Difference Between VARCHAR and CHAR in MySQL
This tutorial will introduce the differences between varchar
and char
in MySQL.
Some of the key points for each are as follows.
CHAR
CHAR
is a fixed space data type that supports strings.- Empty or remaining spaces in the text or string are substituted with blanks or spaces.
CHAR
takes a one-byte size for every character in the input string or text.- Thus, we can say that if we define
CHAR(100)
, it will hold the size of 100 bits no matter what the string length or character count is.
VARCHAR(M)
VARCHAR
has an editable size with a maximum of 65535 characters. The user would have to specify a length between 1 and 65535 characters.- Moreover,
VARCHAR
takesx + 1
bytes of space in the disk where the total number of characters is less than or equal to 255. And it takesx + 2
bytes of space in the disk where the total number of characters is greater than or equal to 256 characters and less than equal to 65535 characters. - Lastly,
VARCHAR
can be a part of an index.
Thus, we can summarize the key differences: varchar
is not fixed length, whereas char
is fixed length or fixed size.
Practically, we can assume that using varchar
is better than using char
datatype. The reason behind this assumption is that a lot of space can be saved with the varchar
datatype.
Let us look at an example to realize the advantage of varchar
.
Say that we define a char
as char(25)
and store the string value as Preet
. On the other hand, let us define another column with data type as varchar
with one string value as Preet
.
Even though these columns with different data types have the value Preet
, varchar
will only consume 5 bits, whereas char
will consume the entire 25 pre-defined bit sizes. The rest of the empty space is padded with char
blanks.
This advantage of varchar
can be massive in production environments where storage is a big issue. Moreover, if we’re using varchar
, we do not need to worry about our string size exceeding a pre-defined bit value.