Data Types

The term VARCHAR stands for VARiable length CHARacter string, and the command takes a numeric value that tells MySQL server the maximum length allowed for a string stored in this field.
Both CHAR and VARCHAR accept text strings and impose a limit on the size of the field. The difference is that every string in a CHAR field has the specified size. If you put in a smaller string, it is padded with spaces. A VARCHAR field does not pad the text; it lets the size of the field vary to fit the text that is inserted. But VARCHAR requires a small amount of overhead to keep track of the size of each value. So, CHAR is slightly more efficient if the sizes are similar in all records, whereas VARCHAR is more efficient if sizes can vary a lot and get large. In addition, the overhead causes access to VARCHAR data to be slightly slower than to CHAR data.

VARCHAR is useful in our example, because it can accommodate author names and titles of different lengths, while helping MySQL plan the size of the database and perform lookups and searches more easily. Just be aware that if you ever attempt to assign a string value longer than the length allowed, it will be truncated to the maximum
length declared in the table definition.


The year field, however, has predictable values, so instead of VARCHAR we use the more efficient CHAR(4) data type. The parameter of 4 allows for 4 bytes of data, supporting all years from –999 to 9999; a byte comprises 8 bits and can have the values 00000000 through 11111111, which are 0 to 255 in decimal. You could, of course, just store two-digit values for the year, but if your data is going to still be needed in the following century, or may otherwise wrap around, it will have
to be sanitized first—think of the “millennium bug” 😀 that would have caused dates beginning on January 1, 2000, to be treated as 1900 on many of the world’s biggest computer installations.

CHAR(n) Exactly n (<= 255) CHAR(5) “Hello” uses 5 bytes and
CHAR(57) “Goodbye” uses 57 bytes.

VARCHAR(n) Up to n (<= 65535) VARCHAR(7) “Hello” uses 5 bytes
VARCHAR(100) “Goodbye” uses 7 bytes.

Leave a Reply

Your email address will not be published. Required fields are marked *