VARCHAR(n)
The variable-length character type (VARCHAR) stores strings of variable length. Unlike fixed-length types, VARCHAR only consumes storage space for the actual content, making it suitable for string data with highly variable lengths.
Syntax
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
n | Integer | Yes | Maximum length of the string, ranging from 1 to 1048576 (approximately 1 MB) |
Value Range
- Minimum length: 1 character
- Maximum length: 1048576 characters (1 MB)
- Storage space is allocated based on actual content length; unused space is not padded with spaces
Examples
-
Create a table with VARCHAR columns:
-
Cast an integer to VARCHAR:
Result:
12345 -
Cast a string to VARCHAR of specified length:
Result:
hello -
Use the maximum length VARCHAR(1048576):
Result:
x -
NULL value handling:
Result:
NULL
Notes
- The maximum length is 1048576 (approximately 1 MB), not 65535. The declared column type
nmust not exceed this value. - When the inserted string length exceeds
n, the behavior (error or truncation) depends on the specific operation. - VARCHAR is case-sensitive; comparisons are performed character by character.
- When storing multi-byte characters (e.g., Chinese characters),
nrepresents the number of characters, not bytes. - If a CAST conversion fails (e.g., converting an incompatible type to VARCHAR), it returns NULL.
