VARCHAR in MySQL
In MySQL, the VARCHAR data type is used to store variable-length character strings. The VARCHAR data type specify a maximum length for the data that can be stored in that column.
Example: Suppose you have a table named Customers, and you want to store email addresses of customers. You decide to use the VARCHAR data type for the Email column, with a maximum length of 50 characters.
CREATE TABLE Customers (
CustomerID INT AUTO_INCREMENT PRIMARY KEY,
Email VARCHAR(50)
);
In this example, the Email column is defined as VARCHAR(50), meaning it can store strings with a maximum length of 50 characters. Unlike CHAR, VARCHAR does not pad spaces. It only uses as much space as needed to store the actual string.
For instance,
INSERT INTO Customers (Email) VALUES ('example@email.com');
between
Output:
In this case, the email address ‘example@email.com’ would be stored as is, occupying only the necessary space to store the string without any padding.
If you attempt to insert a string longer than the specified maximum length, MySQL will truncate the string to fit the defined length.
INSERT INTO Customers (Email) VALUES ('very_long_email_address@example.com');
In this case, ‘very_long_email_address@example.com‘ would be truncated to fit the maximum length of 50 characters.
VARCHAR columns are suitable for storing strings with varying lengths, such as email addresses, names, or descriptions. They are more space-efficient compared to CHAR columns because they only consume as much space as required by the actual data length.
Difference Between CHAR vs VARCHAR in MySQL
MySQL is a widely used relational database management system (RDBMS) that provides a robust and scalable platform for managing and organizing data. MySQL is an open-source software developed by Oracle Corporation, that provides features for creating, modifying, and querying databases. It utilizes Structured Query Language (SQL) to interact with databases, making it a popular choice for web applications and various software systems. MySQL’s versatility, reliability, and ease of use make it a preferred solution for developers and organizations seeking efficient data management capabilities.
In this article, you will learn about, what is the difference between char and varchar in MySQL.