SQL Server VARCHAR(N) Data Type

VARCHAR(N) is a data type in SQL Server used for storing variable-length strings, where N specifies the maximum length of the column, ranging from 1 to 8,000 characters.

Syntax

The syntax for VARCHAR(N) is as follows:

VARCHAR(N)

Where N specifies the maximum length of the column, ranging from 1 to 8,000.

Usage

The VARCHAR(N) data type is typically used for storing variable-length string data, such as addresses, emails, text, descriptions, and comments.

This data type is not suitable for storing binary data. If binary data needs to be stored, the VARBINARY(N) data type should be used instead.

Examples

Here are two examples of using the VARCHAR(N) data type:

Example 1

CREATE TABLE employees (
   id INT PRIMARY KEY,
   name VARCHAR(50) NOT NULL,
   email VARCHAR(100) NOT NULL,
   phone VARCHAR(20),
   address VARCHAR(200)
);

INSERT INTO employees (id, name, email, phone, address)
VALUES (1, 'John Smith', '[email protected]', '(123) 456-7890', '123 Main St, Anytown, USA');

SELECT * FROM employees;

The above example creates a table named employees with columns id, name, email, phone, and address, where name and email columns use the VARCHAR(N) data type.

Example 2

CREATE TABLE products (
   id INT PRIMARY KEY,
   name VARCHAR(50) NOT NULL,
   description VARCHAR(1000),
   price DECIMAL(10, 2) NOT NULL
);

INSERT INTO products (id, name, description, price)
VALUES (1, 'Widget A', 'This is a description of Widget A', 19.99);

SELECT * FROM products;

The above example creates a table named products with columns id, name, description, and price, where name and description columns use the VARCHAR(N) data type.

Conclusion

The VARCHAR(N) data type is one of the common data types used for storing variable-length strings in SQL Server, suitable for storing variable-length string data. When designing database tables, the appropriate data type should be selected according to the actual situation.