In MySQL, string data types are primarily used for storing text. The following are common string data types in MySQL:
-
CHAR: Fixed-length string. When creating a table, the length must be specified, which can be any value between 0 and 255. If the stored string is shorter than the specified length, MySQL pads the remaining characters with spaces to reach the specified length.
Example:
sqlCREATE TABLE example ( column1 CHAR(10) ); INSERT INTO example (column1) VALUES ('hello'); -- Actual storage is 'hello ' (followed by 5 spaces) -
VARCHAR: Variable-length string. Similar to CHAR but does not pad with spaces. If the stored string is shorter than the specified length, no padding is performed. VARCHAR can have a maximum length of 65535 characters.
Example:
sqlCREATE TABLE example ( column1 VARCHAR(10) ); INSERT INTO example (column1) VALUES ('hello'); -- Actual storage is 'hello' -
BLOB: Binary Large Object, used for storing variable amounts of data. There are four types of BLOB: TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB, which differ in the maximum length of data they can store.
-
TEXT: Large text data. Similar to BLOB, it is divided into TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT, which differ primarily in their storage capacity.
Example:
sqlCREATE TABLE example ( column1 TEXT ); INSERT INTO example (column1) VALUES ('This is a longer text...'); -
ENUM: Enumeration type, allowing you to define possible values for a column. During insertion, if the value is not in the enumeration list, the insertion fails or stores the default value (if defined).
Example:
sqlCREATE TABLE example ( column1 ENUM('small', 'medium', 'large') ); INSERT INTO example (column1) VALUES ('medium'); -
SET: A string object that can contain zero or more predefined values, with a maximum of 64.
Example:
sqlCREATE TABLE example ( column1 SET('red', 'green', 'blue') ); INSERT INTO example (column1) VALUES ('red,green');
The choice of these data types depends on the specific application scenario and required storage capacity. For example, for fixed-length small strings, CHAR is appropriate; for strings that may vary in length, VARCHAR is recommended. For scenarios requiring storage of large text, the appropriate TEXT type should be selected.