DEV Community

Tania
Tania

Posted on • Originally published at kodlogs.com

what is the difference between char and varchar?

In a SQL language, the datatype of a column simply means what type of value the column can hold i.e integers, char, long and etc. In that, there are two data types that appear to be the same but have key differences that we will discuss here.

CHAR DATATYPE

  1. It stores character string type of data.
  2. It has a fixed length.
  3. If the length is less than what is specified, then it is padded with extra blank spaces.
  4. It leads to memory wastage.

Example: Consider there is a Table Employee with column id and name. name is of the data type char(5) with size 5. So, If you insert the name ‘Hi’ Now, the length of String is less than the size i.e 5 so, it is padded with extra blank spaces.
Note: This datatype should be used when the values in a column are of the same length.

VARCHAR DATATYPE

  1. By the name itself, we can understand i.e variable.
  2. It also stores character string type of data.
  3. It has a variable length.
  4. If the length is less than what is specified, then it will store as it is without padding.
  5. It saves memory.

Example: Consider the same example, there is a Table Employee with column id and name. name is of the data type char(5) with size 5. So, If you insert the name ‘Hi’ Now, the length of the string is less than the size i.e 5 so now, it won’t do the padding of extra blank spaces.
Note: This datatype should be used when the values in a column are of the variable length.

Important Tip: Performance wise char datatype should get a preference instead of varchar because char takes 1 byte to store each character and varchar takes 1 byte plus extra byte for holding length information.
Thank you for reading this article!!

Top comments (0)