Tuesday, July 31, 2012

What is the difference between CHAR and VARCHAR data types?

CHAR and VARCHAR are the basic built-in types that the SQL standart supports. This short article is about the difference between them.

Difference between CHAR and VARCHAR
CHAR(n)VARCHAR(n)
A fixed-length character string with user-specified length n. A variable-length character string with user-specified maximum length n.

VARCHAR is a short version of "character varying".

The CHAR data type stores fixed length strings. And we should be mindful of this.

For example, if we store a string "test" in the field of type CHAR(10), 6 spaces are appended to the string to make it 10 characters long. In contrast, if we were store the string in the field of type VARCHAR(10), no spaces would be added.

When comparing two values of type CHAR, if they are of different lengths extra spaces are automatically added to the shorter one to make them the same size.

When comparing a CHAR type with a VARCHAR type, extra spaces may not be added (it depends on the database system).

As result, if even the same value "test" is stored in the fields of different types (CHAR and VARCHAR), a comparison of these fields may return false.

Authors of the book "Database System Concepts" Abraham Silberschatz, Henry F. Korth, S. Sudarshan recommend to use the VARCHAR type instead of the CHAR type to avoid these problems.

I used this great book to write the article. The authors of the book are really great men. They did a lot of work writing 1349 pages about database system concepts. I really admire them for doing that.. and enjoy reading the book. Many things become clear.

I'm sure that I'll be better programmer after reading it.