439

What's the difference between VARCHAR and CHAR in MySQL?

I am trying to store MD5 hashes.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
steven
  • 13,147
  • 16
  • 39
  • 39
  • 17
    MD5 hash has always 32 characters. Therefore to maximize your performance use CHAR(32) since CHAR is fixed length (see answers below for more details on differences between CHAR and VARCHAR). – Augustin Feb 26 '16 at 14:39
  • MySQL documentation: [The CHAR and VARCHAR types](https://dev.mysql.com/doc/refman/8.0/en/char.html) – rinogo Nov 29 '21 at 21:44

17 Answers17

430

VARCHAR is variable-length.

CHAR is fixed length.

If your content is a fixed size, you'll get better performance with CHAR.

See the MySQL page on CHAR and VARCHAR Types for a detailed explanation (be sure to also read the comments).

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Anon.
  • 58,739
  • 8
  • 81
  • 86
  • 68
    @steven: when Anon. says "your content is a fixed size" it means the rows of your table must contain all fixed size fields. You get no performance improvement if you use CHAR against VARCHAR in one field, but the table contains other fields that are VARCHAR. – Marco Demaio May 20 '10 at 11:55
  • 2
    no char datatype adds the performance... while execuing the query sql will generate a execution plan. Assume there are 2 columns charcol char(2000) and VarcharCol Varchar(2000).In execution plan,estimated row size for varchar type of columns might be under estimated. thus it leads the spill over to temp db. So using char is good for performance – vignesh Oct 09 '14 at 10:37
  • 1
    what is the meaning of the value in paranthesis of VARCHAR(n) ? – Sivagami Nambi Jul 03 '17 at 16:37
  • @Marco Demaio do you know the reason behind this? – Dehan Aug 09 '17 at 09:38
  • 1
    @jdc91: in order to have a performance increase the whole row has to be fixed-width. MySQL gains advantage calculating the space requirements and offset of rows in that kind of table. – Marco Demaio Oct 17 '17 at 16:42
  • While true I think it is important to point out that during a join the varchar will be expanded to the maximum length and will take that amount of memory – theking2 Jun 17 '23 at 19:52
257

CHAR

  1. Used to store character string value of fixed length.
  2. The maximum no. of characters the data type can hold is 255 characters.
  3. It's 50% faster than VARCHAR.
  4. Uses static memory allocation.

VARCHAR

  1. Used to store variable length alphanumeric data.
  2. The maximum this data type can hold is up to
    • Pre-MySQL 5.0.3: 255 characters.
    • Post-MySQL 5.0.3: 65,535 characters shared for the row.
  3. It's slower than CHAR.
  4. Uses dynamic memory allocation.
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
simplePerson43
  • 3,787
  • 1
  • 15
  • 10
  • 3
    I am slightly surprised that this answer has been upvoted so often. The MySQL documentation states `Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions.` – DroidOS Jun 01 '15 at 09:26
  • 3
    not to mention that you can store alphanumeric data in char too – ninjabber Aug 12 '15 at 09:27
  • 67
    What is this 50% faster based on? 50% faster to do what? In what conditions? And what do you mean by static memory allocation vs dynamic in this context? – Martin Smith Jul 12 '16 at 18:07
  • 10
    @MartinSmith I was gonna ask the same.. don't think that information is accurate. https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2668391900346844476 – rasso Jul 13 '16 at 13:18
  • 1
    The location of a CHAR field to the next CHAR field is predictable and can be calculated. (Versus VARCHAR which always requires a indexed location lookup. A VARCHAR may also be a reference to information stored outside the table-- a pointer.) VARCHAR will save you disk space versus the same data in CHAR columns. Disk space is cheap. You can never get enough speed. Using all fixed length columns and none that are variable, you can enjoy the speed boost. Having one VARCHAR column in your table or any other variable length columns, you might as well have as many other ones you would want. – BradChesney79 Mar 15 '17 at 21:44
  • I am not sure if super fast negligible lookup speeds for SSD drives nullifies the material advantage having all fixed fields provides. – BradChesney79 Mar 15 '17 at 21:45
  • 5
    -1; the performance claims here are vague and unsubstantiated, the difference in memory allocation strategy (and why it matters) isn't fleshed out, and the claim that varchar stores "alphanumeric data" is a bit odd; varchar columns can certainly store non-alphanumeric characters too! – Mark Amery Nov 03 '19 at 17:49
  • 1
    Some information are inaccurate, in what terms CHAR is 50% faster? – Khn Rzk May 29 '21 at 10:46
  • Please explain - "shared for the row part" in "Post-MySQL 5.0.3: 65,535 characters shared for the row." – Payel Senapati Aug 21 '21 at 05:42
138

CHAR Vs VARCHAR

CHAR is used for Fixed Length Size Variable
VARCHAR is used for Variable Length Size Variable.

E.g.

Create table temp
(City CHAR(10),
Street VARCHAR(10));

Insert into temp
values('Pune','Oxford');

select length(city), length(street) from temp;

Output will be

length(City)          Length(street)
10                    6

Conclusion: To use storage space efficiently must use VARCHAR Instead CHAR if variable length is variable

Sampson
  • 265,109
  • 74
  • 539
  • 565
P Sharma
  • 2,638
  • 11
  • 31
  • 35
  • 4
    City = char(10), Street = varchar(10), city = Pune, street = Oxford, length(city) = 4, length(street) = 6 – abdulwadood Feb 10 '16 at 07:09
  • 4
    this query (select length(city), length(street) from temp) is giving following output in mysql 5.7 mysql> select length(city), length(street) from temp; +--------------+----------------+ | length(city) | length(street) | +--------------+----------------+ | 4 | 6 | +--------------+----------------+ 1 row in set (0.00 sec) – Jasbeer Rawal Dec 11 '17 at 03:01
86

A CHAR(x) column can only have exactly x characters.
A VARCHAR(x) column can have up to x characters.

Since your MD5 hashes will always be the same size, you should probably use a CHAR.

However, you shouldn't be using MD5 in the first place; it has known weaknesses.
Use SHA2 instead.
If you're hashing passwords, you should use bcrypt.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 52
    "A CHAR(x) column can only have exactly x characters.". Actually, you can add data with less than x chars, but I think you meant it always RESERVES 10 chars worth of memory behind the scenes. – Dan W Jan 18 '13 at 10:29
  • 16
    You don't know why they're storing md5 hashes, there are many, many valid reasons to use md5 that are nothing to do with security. Collisions are not common at all and the algorithm is faster than more secure ones. – John Hunt Jun 02 '17 at 16:02
  • 2
    Assuming that CHAR(x) column doesn't enforce the x characters exactly is there any reason to use it over VARCHAR(x) even for fixed size data? – Tom Raganowicz May 04 '18 at 07:23
12

What's the difference between VARCHAR and CHAR in MySQL?

To already given answers I would like to add that in OLTP systems or in systems with frequent updates consider using CHAR even for variable size columns because of possible VARCHAR column fragmentation during updates.

I am trying to store MD5 hashes.

MD5 hash is not the best choice if security really matters. However, if you will use any hash function, consider BINARY type for it instead (e.g. MD5 will produce 16-byte hash, so BINARY(16) would be enough instead of CHAR(32) for 32 characters representing hex digits. This would save more space and be performance effective.

reformed
  • 4,505
  • 11
  • 62
  • 88
Grygoriy Gonchar
  • 3,898
  • 1
  • 24
  • 16
  • Following this train of thought, I would use CHAR for business IDs which are meant for readability vs efficiency. I would still use bigint primary keys though. – Archimedes Trajano Jul 24 '15 at 03:16
10

Varchar cuts off trailing spaces if the entered characters is shorter than the declared length, while char will not. Char will pad spaces and will always be the length of the declared length. In terms of efficiency, varchar is more adept as it trims characters to allow more adjustment. However, if you know the exact length of char, char will execute with a bit more speed.

Gigazelle
  • 1,424
  • 1
  • 24
  • 34
user1445657
  • 109
  • 1
  • 3
9

CHAR is fixed length and VARCHAR is variable length. CHAR always uses the same amount of storage space per entry, while VARCHAR only uses the amount necessary to store the actual text.

Donnie DeBoer
  • 2,517
  • 15
  • 14
9

CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.

Andrew
  • 129
  • 3
  • While I'd *guess* that the claims about speed and storage efficiency here are true, neither of them are substantiated in any way (and it's perfectly plausible that they're false), which makes this answer non-useful; it just repeats what the reader probably already would've expected to be true, without doing anything to truly help confirm it. – Mark Amery Nov 03 '19 at 17:53
9

In most RDBMSs today, they are synonyms. However for those systems that still have a distinction, a CHAR field is stored as a fixed-width column. If you define it as CHAR(10), then 10 characters are written to the table, where "padding" (typically spaces) is used to fill in any space that the data does not use up. For example, saving "bob" would be saved as ("bob"+7 spaces). A VARCHAR (variable character) column is meant to store data without wasting the extra space that a CHAR column does.

As always, Wikipedia speaks louder.

Greg Fenton
  • 1,233
  • 9
  • 15
  • I don't agree that "they are synonyms". MySQL, for one, seems to directly contradict this claim. *"The CHAR and VARCHAR types are similar, but differ in the way they are stored and retrieved..."* ([Source](https://dev.mysql.com/doc/refman/8.0/en/char.html)) – rinogo Nov 29 '21 at 21:42
  • 1
    "In most"...and "today" was 12 years ago :) – Greg Fenton Nov 30 '21 at 22:09
  • You’re right! Might be valuable to others to update the answer. – rinogo Nov 30 '21 at 22:10
5

CHAR

  • CHAR is a fixed length string data type, so any remaining space in the field is padded with blanks.
  • CHAR takes up 1 byte per character. So, a CHAR(100) field (or variable) takes up 100 bytes on disk, regardless of the string it holds.

VARCHAR

  • VARCHAR is a variable length string data type, so it holds only the characters you assign to it.
  • VARCHAR takes up 1 byte per character, + 2 bytes to hold length information (For example, if you set a VARCHAR(100) data type = ‘Dhanika’, then it would take up 7 bytes (for D, H, A, N, I, K and A) plus 2 bytes, or 9 bytes in all.)
Dhanika
  • 749
  • 7
  • 12
5

CHAR

  1. Uses specific allocation of memory
  2. Time efficient

VARCHAR

  1. Uses dynamic allocation of memory
  2. Memory efficient
SAKIB
  • 475
  • 5
  • 7
1

The char is a fixed-length character data type, the varchar is a variable-length character data type.

Because char is a fixed-length data type, the storage size of the char value is equal to the maximum size for this column. Because varchar is a variable-length data type, the storage size of the varchar value is the actual length of the data entered, not the maximum size for this column.

You can use char when the data entries in a column are expected to be the same size. You can use varchar when the data entries in a column are expected to vary considerably in size.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Bob Minteer
  • 149
  • 3
1

Distinguishing between the two is also good for an integrity aspect.

If you expect to store things that have a rule about their length such as yes or no then you can use char(1) to store Y or N. Also useful for things like currency codes, you can use char(3) to store things like USD, EUR or AUD.

Then varchar is better for things were there is no general rule about their length except for the limit. It's good for things like names or descriptions where there is a lot of variation of how long the values will be.

Then the text data type comes along and puts a spanner in the works (although it's generally just varchar with no defined upper limit).

TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106
0

according to High Performance MySQL book:

VARCHAR stores variable-length character strings and is the most common string data type. It can require less storage space than fixed-length types, because it uses only as much space as it needs (i.e., less space is used to store shorter values). The exception is a MyISAM table created with ROW_FORMAT=FIXED, which uses a fixed amount of space on disk for each row and can thus waste space. VARCHAR helps performance because it saves space.

CHAR is fixed-length: MySQL always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. (This was also true of VARCHAR in MySQL 4.1 and older versions—CHAR and VAR CHAR were logically identical and differed only in storage format.) Values are padded with spaces as needed for comparisons.

Alireza Rahmani Khalili
  • 2,727
  • 2
  • 32
  • 33
  • 2
    "_VARCHAR helps performance because it saves space_" It saves space, yes, but doesn't it negatively affect performace? `VARCHAR` needs to dynamically allocate memory as and when required thus reducing performance as opposed to `CHAR`, right? – Spikatrix Apr 23 '19 at 06:00
  • @Spikatrix Depends. If VARCHAR values are often small but could be up to N bytes, then dynamic allocation could save a significant amount of space and I/O, which is more performant for lots of data. CHAR values which are roughly equal in length would be more performant. Reads vs. writes also probably makes a difference. – Andrew Jun 11 '19 at 19:51
  • The point of a fixed-length datatype is that the offset is predictable, i.e if you save an array of CHAR(M) to disk, you know that item N is at byte offset sizeof(char(M))*N. So very fast lookup with no overhead (index etc). For varying length VARCHARS you couldn't use such a simple and efficient approach. – Alexander Torstling Nov 22 '21 at 17:52
-4

Char has a fixed length (supports 2000 characters), it is stand for character is a data type

Varchar has a variable length (supports 4000 characters)

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
-6

Char or varchar- it is used to enter texual data where the length can be indicated in brackets Eg- name char (20)

Amy
  • 1
  • This does not address the original question. OP is asking the practical differences between the types, not the syntax and purpose of the types. Also `(` and `)` are parentheses, not brackets. – 2mac Jul 22 '15 at 16:26
  • @2mac your final sentence is only true of American English; in Britain we call `(` and `)` brackets, and many Brits probably don't even realize that there are dialects of English in which the word "parenthesis" can refer to a punctuation mark. There's a strong case to be made for preferring "parentheses" to "brackets" - it's probably, on balance, the maximally clear option when targeting an international audience of programmers - but it's a more complicated case than "brackets" just being wrong. – Mark Amery Dec 23 '17 at 11:40
-11

CHAR :

  • Supports both Character & Numbers.
  • Supports 2000 characters.
  • Fixed Length.

VARCHAR :

  • Supports both Character & Numbers.
  • Supports 4000 characters.
  • Variable Length.

any comments......!!!!