Detailed description of the correct use of strings in the MySQL database _ MySQL

Source: Internet
Author: User
This article describes how to correctly use strings in MySQL databases. it mainly describes the actual operation steps of MySQL database characters (strings). We all know the characters (strings) of MySQL database) in practice, it is often used, so you have better understanding of it and hope to bring you some help in this aspect.

Do not assume that the character type is CHAR in the MySQL database. The difference between CHAR and VARCHAR is that CHAR is of fixed length, as long as you define a field as CHAR (10 ), therefore, no matter whether the data you store reaches 10 bytes, it occupies 10 bytes of space, while VARCHAR is of a variable length, if the possible value of a field is not fixed, we only know that it cannot exceed 10 characters. it is the most cost-effective to define it as VARCHAR (10, the occupied space of the VARCHAR type is the actual length of its value plus 1.

Why + 1? This byte is used to save the actual length. From this + 1, we can also see that if a field has a maximum of 10 characters, and in most cases, it uses 10 characters, it is not feasible to use VARCHAR: in most cases, the actual occupied space is 11 bytes, occupying one more byte than CHAR (10.

For example, a table stores the stock name and code. The stock name is mostly in four words, that is, 8 bytes. the stock code is a six-digit number in Shanghai, shenzhen has four digits. These are fixed length, and the stock name must use CHAR (8). although the stock code is not fixed length, if VARCHAR (6) is used ), A stock code in Shenzhen actually occupies 5 bytes, while a stock code in Shanghai occupies 7 bytes! Considering that Shanghai has more shares than Shenzhen, VARCHAR (6) is not as good as CHAR (6.

Although the maximum length of a CHAR or VARCHAR can be up to 255, I think CHAR larger than 20 is almost useless.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.