Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any benefit of uses CHAR over VARCHAR?

Tags:

mysql

CHAR is stored as a fixed length string, VARCHAR is stored as a variable length string. I can use VARCHAR to store a fixed length string, but why people still want to use CHAR to store a fixed length string? Is there any benefit of using CHAR over VARCHAR? If none of benefit, why mySQL database doesn't remove the option of CHAR?

like image 969
zac1987 Avatar asked Sep 29 '11 17:09

zac1987


1 Answers

  • VARCHAR

varchar stores variable-length character string. it can require less storage than fixed-length types because it uses only as much space as it needs.

varchar also uses 1 or 2 extra bytes to record the value's length. for example varchar(10) will use up to 11 bytes of storage space. varchar helps performance because it saves space. however because the rows are variable length, they can grow when you update them, which can cause extra work. if a row grows and no longer fits in its original location, the behavior is storage engine-dependent...

  • CHAR

char is fixed-length , mysql always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. Values are padded with spaces as needed for comparisons.

char is useful if you want to store very short strings, or if all the values are nearly the same length. For example, CHAR is a good choice for MD5 values for user passwords, which are always the same length.

char is also better than VARCHAR for data that’s changed frequently, because a fixed-length row is not prone to fragmentation.

like image 197
Don Gorgon Avatar answered Sep 24 '22 08:09

Don Gorgon