What are the differences between CHAR and VARCHAR data types in MySQL?

Both CHAR and VARCHAR data types are used to store string data in the field of the table. The differences between these data types are mentioned below:

  • CHAR data type is used to store fixed-length string data and the VARCHAR data type is used to store variable-length string data. For example: Use CHAR data type to store the values that has fixed length, like country code. For values that has variable length like names or titles use VARCHAR to save the space.
  • The CHAR data type allows you to store fixed-length strings with a maximum size of 255 characters. Whereas the VARCHAR data type allows you to store variable-length strings with a maximum size of 65,535 characters (it was limited to 255 characters prior to MySQL 5.0.3).
  • The storage size of the CHAR data type will always be the maximum length of this data type and the storage size of VARCHAR will be the length of the inserted string data. Hence, it is better to use the CHAR data type when the length of the string will be the same length for all the records.
  • CHAR is used to store small data whereas VARCHAR is used to store large data.
  • CHAR works faster and VARCHAR works slower.
  • When values are stored in a CHAR column, they are right-padded with spaces to the specified length, but in VARCHAR column values are not padded when they are stored. This means if you store the value 'ab' in a CHAR(4) column the value will be stored as 'ab  ', whereas the same value will be stored in VARCHAR(4) column as 'ab'.

Example:

CREATE TABLE location (
id INT AUTO_INCREMENT PRIMARY KEY,
address VARCHAR(50),
country_code CHAR(3));