Difference Between CHAR and VARCHAR in MySQL

MySQL


Difference Between CHAR and VARCHAR in MySQL

What is the difference between CHAR and VARCHAR in SQL?

First, to show how they are similar, CHAR and VARCHAR are both variable types that hold string characters. For example, CHAR and VARCHAR can hold string text such as 'David', 'Peter', 'Bill' and so on. They hold string characters, not numbers.

CHAR and VARCHAR are also similar in that they are fixed lengths. When you declare CHAR(10) and VARCHAR(10), they each can only hold a maximum of 10 characters and no more. If you input into them a string such as 'dancingwiththestars', both CHAR and VARCHAR will only produce 'dancingwit' in return.

The difference now between the two is what occurs to shorter words. If you declare CHAR(10), it must fill up 10 spaces. So if you input the string 'Peter' into it, 'Peter     ' (Peter followed by 5 spaces) will be returned. However, if you declare VARCHAR and place the string 'Peter' into it, it will return 'Peter' as output with no spaces. This is because VARCHAR automatically cuts off all trailing spaces, while with CHAR all the padding spaces are included.

In practice, programmers rarely use CHAR because VARCHAR is more adaptable and almost always provides the behavior that is wanted.

HTML Comment Box is loading comments...