A2-04-03.MySQL DATA TYPES-MySQL CHAR Data Type

时间:2022-04-10 00:16:45

转载自:http://www.mysqltutorial.org/mysql-char-data-type/

MySQL CHAR Data Type

 

Summary: in this tutorial, you will learn about MySQL CHAR data type and how to apply it in your database table design.

Introduction to MySQL CHAR data type

The CHAR data type is a fixed-length character type in MySQL. We often declare the CHAR type with a length that specifies the maximum number of characters that we want to store. For example, CHAR(20)can hold up to 20 characters.

If the data that you want to store is a fixed size, you should use the CHAR data type. You’ll get a better performance in comparison with VARCHAR in this case.

The length of the CHAR data type can be any value from 0 to 255. When you store a CHAR value, MySQL pads its value with spaces to the length that you declared.

When you query the CHAR value, MySQL removes the trailing spaces.

Note that MySQL will not remove the trailing spaces if you enable the PAD_CHAR_TO_FULL_LENGTHSQL mode.

The following statement creates a table with a CHAR column.

The status column has the CHAR data type. It can hold up to 3 characters.

Now, we insert 2 rows into the mysql_char_test table.

We use the length function to get the length of each CHAR value.

A2-04-03.MySQL DATA TYPES-MySQL CHAR Data Type

The following statement inserts a CHAR value with the leading and trailing spaces.

However, when we retrieve the value, MySQL removes the trailing space.

A2-04-03.MySQL DATA TYPES-MySQL CHAR Data Type

Comparing MySQL CHAR values

When storing or comparing the CHAR values, MySQL uses the character set collation assigned to the column.

MySQL does not consider trailing spaces when comparing CHAR values using the comparison operator such as =, <>, >, <, etc.

Notice that the LIKE operator does consider the trailing spaces when you do pattern matching with CHAR values.

In the previous example, we stored the value Y with both leading and trailing spaces. However, when we execute the following query:

MySQL returns no row because it does not consider the trailing space. To match with the ‘ Y ‘, we need to remove the trailing space as follows:

A2-04-03.MySQL DATA TYPES-MySQL CHAR Data Type

MySQL CHAR and UNIQUE index

If the CHAR column has a UNIQUE index and you insert a value that is different from an existing value in a number of trailing spaces, MySQL will reject the changes because of duplicate-key error.

See the following example.

First, create a unique index for the status column of the mysql_char_test table.

Second, insert a new row into the mysql_char_test table.

Third, insert the following value will cause a duplicate-key error.

 

In this tutorial, we have introduced you to the MySQL CHAR data type and its features. Now, you should have a good understanding of the CHAR data type to apply it in your database design.