Introduction to MySQL CHAR Data Type

CHAR is a data type in MySQL used for storing fixed-length string data.

Syntax

The syntax for CHAR data type is as follows:

CHAR(M)

Where M represents the length of the field. It can be set to a maximum of 255. If longer lengths are required, VARCHAR data type can be used instead.

Use Cases

CHAR data type is commonly used for storing fixed-length strings, such as postal codes, phone numbers, etc.

Compared to VARCHAR data type, CHAR stores fixed-length strings, which makes it faster in queries. However, if the stored string is shorter than the specified length, it will be automatically padded with spaces at the end, which may result in wasted storage space.

Examples

Here are two examples of using CHAR data type:

CREATE TABLE employee (
  emp_id INT PRIMARY KEY,
  emp_name CHAR(20),
  emp_phone CHAR(10)
);

INSERT INTO employee (emp_id, emp_name, emp_phone)
VALUES (1, 'John Doe', '555-1234');

SELECT * FROM employee;

In the above example, we create a table named employee with three fields: emp_id, emp_name, and emp_phone. The length of emp_name and emp_phone is set to 20 and 10 respectively.

Then, we insert a record into the table and use a SELECT statement to view all the data in the table.

Conclusion

CHAR data type is suitable for storing fixed-length strings, with faster query performance but potential storage space wastage.