In SQL, VARCHAR is a data type used to represent character string values of variable length. The term VARCHAR stands for Variable Character. It is one of the most commonly used data types in SQL, especially for storing textual data such as names, addresses, and descriptions.
Syntax
The syntax for defining a VARCHAR data type is as follows:
VARCHAR(length)
Example
Here, length is the maximum number of characters that can be stored in the VARCHAR column. For example, if you want to create a table with a column to store names, where the maximum length of the name is 50 characters, you can use the following SQL command:
CREATE TABLE students ( id INT PRIMARY KEY, name VARCHAR(50) );
In this example, the name column is defined as a VARCHAR data type with a maximum length of 50 characters. This means that any value stored in the name column can be up to 50 characters long.
You can also use the VARCHAR data type in SQL queries to filter and search for specific values. For example, to select all the students with names starting with “J”, you can use the following query:
SELECT * FROM students WHERE name LIKE 'J%';
This query selects all the rows from the students table where the name column starts with the letter “J”. The % symbol is a wildcard that matches any number of characters, so this query selects all names that start with “J” regardless of their length.
One of the advantages of using VARCHAR over a fixed-length character data type like CHAR is that it allows for more efficient storage of data. With VARCHAR, the database system only allocates enough space to store the actual string value, rather than allocating a fixed amount of storage regardless of the actual length of the string. This can lead to significant space savings, especially when storing large amounts of text data.
It’s important to note that VARCHAR is not suitable for storing binary data, such as images or executable code.
In addition to specifying the maximum length of the VARCHAR column, it’s also possible to set a minimum length using the optional keyword CHECK. For example, VARCHAR(50) CHECK (LEN(column_name) >= 3) would specify a minimum length of 3 characters for the column.
In summary, VARCHAR is a flexible data type used for storing variable-length character data in SQL. Its efficient storage characteristics make it a popular choice for storing textual data, while its flexibility allows for precise control over the maximum and minimum length of the stored strings.