A2-04-12.MySQL DATA TYPES- The Essential Guide to MySQL VARCHAR Data Type

时间:2022-04-10 16:31:18

转载自:http://www.mysqltutorial.org/mysql-varchar/

The Essential Guide to MySQL VARCHAR Data Type

 

Summary: this tutorial introduces you to the MySQL VARCHAR data type and discusses some important features of VARCHAR.

Introduction to MySQL VARCHAR data type

MySQL VARCHAR is the variable-length string whose length can be up to 65,535. MySQL stores a VARCHARvalue as a 1-byte or 2-byte length prefix plus actual data.

The length prefix specifies the number of bytes in the value. If a column requires less than 255 bytes, the length prefix is 1 byte. In case the column requires more than 255 bytes, the length prefix is two length bytes.

The maximum length, however, is subject to maximum row size (65,535 bytes) and the character setused. It means that the total length of all columns should be less than 65,535 bytes.

Let’s take a look at an example.

We will create a new table that has two columns s1 and s2 with the length of 32765(+2 for length prefix) and 32766 (+2).Note that 32765+2+32766+2=65535, which is the maximum row size.

The statement created the table successfully. However, if we increase the length of the s1 column by 1.

MySQL will issue the error message:

As you can see, the row size is too large and the statement failed.

If you insert a string whose length is greater than the length of a VARCHAR column, MySQL will issue an error. Consider the following example:

In this example, MySQL issued the following error message:

 

MySQL VARCHAR and spaces

MySQL does not pad space when it stores the VARCHAR values. Also, MySQL retains the trailing spaces when it inserts or selects VARCHAR values. See the following example:

 

A2-04-12.MySQL DATA TYPES- The Essential Guide to MySQL VARCHAR Data Type

However, MySQL will truncate the trailing spaces when inserting a VARCHAR value that contains trailing spaces which cause the column length exceeded. In addition, MySQL issues a warning. Let’s see the following example:

This statement inserts a string whose length is 4 into the title column. MySQL still inserts the string, however, it truncates the trailing space before inserting the value.

You can verify it by using the following query:

A2-04-12.MySQL DATA TYPES- The Essential Guide to MySQL VARCHAR Data Type

In this tutorial, you have learned how to use MySQL VARCHAR data type to store variable strings in the database.