views:

98

answers:

2

I understand the differences between CHAR and VARCHAR, one being fixed-length and the other variable-length, and that if all fields in a row are fixed-length, a table will generally perform better.

However, something that is unclear to me is that if I give VARCHAR a length, such as VARCHAR(500), does this retain the row as fixed-length?

For context, I have clean table with 50 columns, mostly TINYINTs, but I need two columns in this table as VARCHAR, as they will need store up to 500 characters each. The exact length is subject to user input and therefore unknown.

As an additional qualification, I don't really want to put these VARCHAR fields into a separate referenced table as it produces unnecessary joins and doesn't fit the expected query patterns very efficiently.

Any help would be appreciated. Thanks.

A: 

No, it just sets the max size.

The CHAR and VARCHAR types are declared with a length that indicates the maximum number of characters you want to store. For example, CHAR(30) can hold up to 30 characters.

code_burgar
Thanks for the answer
Tom
+2  A: 

Obviously no, otherwise it wouldn't be called variable-length in the first place. What it simply does is put a cap on the maximum length of the strings that you can store inthat column. On other, more trustable database engines, strings which are longer than the max will produce an error, but MySQL just truncates excess data:

mysql> create table t (a varchar(3));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into t values ('abc'), ('defgh');
Query OK, 2 rows affected, 1 warning (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 1

mysql> select * from t;
+------+
| a    |
+------+
| abc  |
| def  |
+------+
2 rows in set (0.00 sec)
Antoine P.
Ok, thanks for the answer.
Tom
Also remember that a varchar will actually use more storage per record than the number of bytes in the string. It does this to store the string length as well as the string.E.g. if you use varchar(5) , and all records have the field filled with 5 chars, then 6 bytes will be used per record. a char(5) will use only 5 bytes for each record.This can make a difference when you have millions of rows! Although in that case, a lookup table with an integer id reference may be better for performance - especially if any of the data within the field is duplicated across many rows.Hope that helps.
Dave Rix