MySQL VARCHAR类型字段到底可以定义多长

来源:这里教程网 时间:2026-03-01 15:23:38 作者:

MySQL 单行行长最大是65535,不包含TEXT,BLOB类型。varchar 长度小于255时,需要额外使用1字节存储长度,大于255时,需要 额外使用2字节存储长度。 varchar 栏位如果不定义not null 时,默认null也需要占1字节lantin1字符集存储的每个值占1字节gbk 字符集存储的每个值占2字节 utf8 字符集存储的每个值占3字节 那么一行varchar到底可以定义多长呢? lantin1长度=65535-存储长度大小 - default NULL大小 gbk长度=(65535-存储长度大小 - default NULL大小)/2 utf8长度=(65535-存储长度大小 - default NULL大小)/3 举例说明: lantin1情况 lantin1 varchar设置两个字段sno小于255( 额外使用1字节存储长度),sname大于255( 额外使用2字节存储长度),所以单行varchar最大长度为: 

mysql> select 65535-1-2;
+-----------+
| 65535-1-2 |
+-----------+
|     65532 |
+-----------+
1 row in set (0.00 sec)

sno varchar(1) not null+sname varchar(65531) not null=65532,建表成功

mysql> create table my8(sno varchar(1) not null,sname varchar(65531) not null, primary key(sno)) CHARSET=latin1;
Query OK, 0 rows affected (0.03 sec)
mysql> drop table my8 ;
Query OK, 0 rows affected (0.01 sec)

再看sno varchar(1) not null+sname varchar(65532) not null>65532,建表失败

mysql> create table my8(sno varchar(1) not null,sname varchar(65532) not null, primary key(sno)) CHARSET=latin1;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

如指定 not null  sno varchar(1) sname varchar(65531) 就不行,因为有一个隐含的default null还占用1字节,建表失败

mysql> create table my8(sno varchar(1),sname varchar(65531) , primary key(sno)) CHARSET=latin1;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

UTF8情况 UTF8 varchar设置两个字段sno小于255(额外使用1字节存储长度),sname大于255(额外使用2字节存储长度),utf8字符集存储的每个值占3字节,所以单行varchar最大长度为: 

mysql> select (65535-1-2)/3;
+---------------+
| (65535-1-2)/3 |
+---------------+
|    21844.0000 |
+---------------+
1 row in set (0.00 sec)

sno varchar(1) not null+sname varchar(21844) not null>21844,建表失败

mysql> create table my8(sno varchar(1) not null,sname varchar(21844) not null, primary key(sno)) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

sno varchar(1) not null+sname varchar(21843) not null=21844,建表成功

mysql> create table my8(sno varchar(1) not null,sname varchar(21843) not null, primary key(sno)) CHARSET=utf8;
Query OK, 0 rows affected (0.02 sec)

相关推荐