MySQL CHAR

The CHAR data type in MySQL is used to store fixed-length strings. When you define a column with the CHAR data type, you specify a fixed length for the string, and any shorter values are padded with spaces to meet that length. This ensures that the stored data always occupies the specified number of characters.

Syntax

Here’s a basic syntax for creating a table with a CHAR column in MySQL:

CREATE TABLE example_table (
    char_column CHAR(length)
);

In this syntax:

example_table is the name of the table.
char_column is the name of the column.
CHAR is the data type.
length is the number of characters to store in the column.

Example

For example, if you want to create a table with a CHAR column that can store names with a maximum length of 50 characters, you would use the following SQL statement:

CREATE TABLE person (
    full_name CHAR(50)
);

Now, if you insert a name that is shorter than 50 characters, MySQL will automatically pad it with spaces to meet the specified length.

INSERT INTO person (full_name) 
VALUES ('John Doe');

The data in the full_name column will be stored as ‘John Doe’ followed by spaces to fill up the remaining characters.

It’s important to note that the CHAR data type is fixed-length, which means it can be less space-efficient for storing variable-length strings compared to other data types like VARCHAR. In situations where the length of the data can vary significantly, using VARCHAR might be a more appropriate choice.

In summary, the CHAR data type in MySQL is useful when you need to store fixed-length strings, and it ensures that the stored data always occupies the specified number of characters by padding with spaces if necessary.