In MySQL, vARCHar and char are both types that can store strings, and when designing tables, you must specify the length explicitly!
Varchar is variable length. Suppose a field is designed as vARCHar (10). If a” Java “string is stored and 4 characters are actually stored, the space occupied is also 4 characters.
Varchar (10); char(10); varchar(10); char(10);
Therefore, if the length of the string to be stored is not fixed, use the vARCHar type, and only use char if the length is fixed.
When MySQL processes a vARCHAR type, by default it also uses an extra byte to record the “actual number of characters saved”, that is, by storing “Java” into the field of vARCHar (10), MySQL also uses an extra byte to record the value of 4. Later, when reading this value, MySQL will read the 4 first and then start fetching data from the field; Char does not have this problem, because strings stored using char must have a fixed length (and even if they are not, Spaces are added so that all strings in the field have the same length as the field’s design value).
Of course, when dealing with vARCHAR types, by default only 1 byte is used to record the “actual number of characters saved”, so the maximum number of characters that can be saved in this case is 255 (the maximum positive value of 1 word). When more data needs to be saved, MySQL automatically expands. Use 2 bytes to record the “actual number of characters stored”, can represent the maximum number of positive is 65535, and will not be expanded, so use VARCHar to store up to 65535 characters!
Therefore, vARCHAR data takes up more storage space (requires extra bytes for recording), and the query efficiency is low. Therefore, data that can be stored by using CHAR can be stored and used by using VARCHar. However, in the application scenarios that can use CHAR, the data can be stored and used by using VARCHar. Char should be used in preference.