Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any point in using CHAR if you have a VARCHAR in the same table?

I just read the accepted answer of this question, which left me with this question.

Here's a quote from that answer:

"But since you tagged this question with MySQL, I'll mention a MySQL-specific tip: when your query implicitly generates a temporary table, for instance while sorting or GROUP BY, VARCHAR fields are converted to CHAR to gain the advantage of working with fixed-width rows. If you use a lot of VARCHAR(255) fields for data that doesn't need to be that long, this can make the temporary table very large."

As I understand it, the advantage of CHAR is that you get fixed-width rows, so doesn't a VARCHAR in the same table mess that up? Are there any advantages of using CHAR when you have a VARCHAR in the same table?


Here's an example:

Table with CHAR:

CREATE TABLE address (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    street VARCHAR(100) NOT NULL,
    postcode CHAR(8) NOT NULL,
    PRIMARY KEY (id)
);

Table without CHAR:

CREATE TABLE address (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    street VARCHAR(100) NOT NULL,
    postcode VARCHAR(8) NOT NULL,
    PRIMARY KEY (id)
);

Will the table with CHAR perform any better than the table without CHAR, and if so, in what situations?

like image 400
Erik B Avatar asked Nov 05 '22 03:11

Erik B


1 Answers

"VARCHAR" basically sets a maximum length for the field and only stores the data that is entered into it, thus saving on space. The "CHAR" type has a fixed length, so if you set "CHAR(100)", 100 character worth of space will be used regardless of what the contents are.

The only time you will gain a speed advantage is if you have no variable length fields in your record ("VARCHAR", "TEXT", etc.). You may notice that Internally all your "CHAR" fields are changed to "VARCHAR" as soon as a variable length field type is added, by MySQL.

Also "CHAR" is less efficient from a space storage point of view, but more efficient for searching and adding. It's faster because the database only has to read an offset value to get a record rather than reading parts until it finds the end of a record. And fixed length records will minimize fragmentation, since deleted record space can be reused for new records.

Hope it helps.

like image 54
Knowledge Craving Avatar answered Nov 09 '22 11:11

Knowledge Craving