In SQL Server, the VARCHAR
data type is used to store variable-length character strings. It can store character strings with a maximum length of 8,000 characters.
When a table is created, you can specify the VARCHAR
data type for a column and also specify the maximum length of the string that can be stored in that column.
For example, a column defined as VARCHAR(50) can store character strings with a maximum length of 50 characters.
The VARCHAR
data type is often used to store alphanumeric data such as names, addresses, or descriptions.
It is also commonly used to store variable-length text data in a table, such as the body of an email or the content of a blog post.
It is important to note that when using VARCHAR
, SQL Server will store the actual length of the string and not the maximum length, this means it will take up more storage space, if you know the length of the string you can use CHAR
, which stores the string at its maximum length.
VARCHAR syntax
varchar [ ( n ) ]
varchar [ ( max ) ]
VARCHAR example
USE model;
GO
CREATE TABLE varcharTable ( a varchar(10) );
GO
INSERT INTO varcharTable VALUES ('abcdefghij');
GO
SELECT a FROM varcharTable;
GO
Result |
---|
abcdefghij |
USE model;
GO
DECLARE @myVar AS varchar(20) = 'abc123';
SELECT @myVar as 'My column', DATALENGTH(@myVar) as 'Length';
GO
My column | Length |
---|---|
abc123 | 6 |
Summary: On Transact SQL language the varchar is part of character strings data types and have variable length. The string length must be a value from 1 through 8,000.