每次建立一个新的SQL表或向现有表添加一个新的varchar列时,我都想知道一件事:长度的最佳值是多少。

假设,你有一个列名为name类型为varchar。所以,你必须选择长度。我想不出一个20个字符的名字,但你永远不会知道。但不是用20,我总是四舍五入到下一个2^n。在这种情况下,我将选择32作为长度。我这样做,是因为从计算机科学家的角度来看,2^n这个数字在我看来比其他数字更均匀,我只是假设下面的架构可以比其他数字更好地处理这些数字。

另一方面,以MSSQL服务器为例,当您选择创建varchar列时,将默认长度值设置为50。这让我开始思考。为什么50 ?它只是一个随机数,还是基于平均列长,还是什么?

也可能是——或者可能是——不同的SQL服务器实现(如MySQL, MSSQL, Postgres,…)有不同的最佳列长度值。


当前回答

VARCHAR(255)和VARCHAR(2)在磁盘上占用的空间完全相同!所以限制它的唯一原因是如果你有特定的需要让它更小。否则都设为255。

具体来说,在进行排序时,较大的列确实会占用更多的空间,因此如果这会影响性能,那么您需要担心它,并将其减小。但如果你只从表中选择了一行,那么你可以把它们都设为255,这没有关系。

参见:MySQL的最佳varchar大小是多少?

其他回答

最佳值是基础域中定义的数据的正确值。

对于某些域,VARCHAR(10)适合Name属性,对于其他域,VARCHAR(255)可能是最佳选择。

VARCHAR(255)和VARCHAR(2)在磁盘上占用的空间完全相同!所以限制它的唯一原因是如果你有特定的需要让它更小。否则都设为255。

具体来说,在进行排序时,较大的列确实会占用更多的空间,因此如果这会影响性能,那么您需要担心它,并将其减小。但如果你只从表中选择了一行,那么你可以把它们都设为255,这没有关系。

参见:MySQL的最佳varchar大小是多少?

I haven't checked this lately, but I know in the past with Oracle that the JDBC driver would reserve a chunk of memory during query execution to hold the result set coming back. The size of the memory chunk is dependent on the column definitions and the fetch size. So the length of the varchar2 columns affects how much memory is reserved. This caused serious performance issues for me years ago as we always used varchar2(4000) (the max at the time) and garbage collection was much less efficient than it is today.

经常向您的业务领域专家咨询。如果你是这样,那就寻找一个行业标准。例如,如果所讨论的域名是一个自然人的姓氏,那么对于一家英国企业,我会去英国政府谈话数据标准目录查找个人信息,并发现一个姓氏将在1到35个字符之间。

添加到a_horis_with_no_name的答案中,您可能会发现以下内容令人感兴趣……

是否将列声明为没有任何区别 VARCHAR(100)或VACHAR(500)。

-- try to create a table with max varchar length
drop table if exists foo;
create table foo(name varchar(65535) not null)engine=innodb;

MySQL Database Error: Row size too large.

-- try to create a table with max varchar length - 2 bytes for the length
drop table if exists foo;
create table foo(name varchar(65533) not null)engine=innodb;

Executed Successfully

-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65533))engine=innodb;

MySQL Database Error: Row size too large.

-- try to create a table with max varchar length with nullable field
drop table if exists foo;
create table foo(name varchar(65532))engine=innodb;

Executed Successfully

不要忘记长度字节(s)和可空字节,这样:

Name varchar(100) not null将是1字节(长度)+最多100个字符(latin1)

Name varchar(500) not null将是2字节(长度)+最多500个字符(latin1)

Name varchar(65533) not null将是2字节(长度)+ 65533个字符(latin1)

名称varchar(65532)将是2个字节(长度)+最多65532个字符(latin1) + 1个空字节

希望这对你有所帮助。