Mimi Chan
Mimi Chan

Reputation: 111

Is char or varchar better for a database with utf-8 encoding?

I am making a table of users where I will store all their info: username, password, etc. My question is: Is it better to store usernames in VARCHAR with a utf-8 encoded table or in CHAR. I am asking because char is only 1 byte and utf-8 encodes up to 3 bytes for some characters and I do not know whether I might lose data. Is it even possible to use CHAR in that case or do I have to use VARCHAR?

Upvotes: 1

Views: 325

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269763

In general, the rule is to use CHAR encoding under the following circumstances:

  • You have short codes that are the same length (think state abbreviations).
  • Sometimes when you have short code that might differ in length, but you can count the characters on one hand.
  • When powers-that-be say you have to use CHAR.
  • When you want to demonstrate how padding with spaces at the end of the string causes unexpected behavior.

In other cases, use VARCHAR(). In practice, users of the database don't expect a bunch of spaces at the end of strings.

Upvotes: 2

Related Questions