What is the difference between CHAR and VARCHAR

In MySQL, CHAR and VARCHAR are two data types used to store string data, but they have some key differences:

  • CHAR: This data type is used to store fixed-length strings. It allocates a set amount of space regardless of the actual length of the string entered. For example, if you define a column as CHAR(10) and enter 'hello', it will still use 10 characters of space, with the remaining space padded with spaces.
  • VARCHAR: This data type is used to store variable-length strings. It only uses as much space as necessary for the stored string, plus one or two additional bytes to hold the length of the string. For example, if you define a column as VARCHAR(10) and enter 'hello', it only uses 5 characters of space.

Here is an example of how to define CHAR and VARCHAR columns in a MySQL table:

CREATE TABLE example ( fixed_length CHAR(10), variable_length VARCHAR(10) );

MySQL CHAR VARCHAR data types string storage database design