我意识到,如果我的所有值都是固定宽度的,建议使用CHAR。但是,那又怎样?为了安全起见,为什么不为所有文本字段选择VARCHAR呢?
当前回答
碎片。Char会保留空间,而VarChar则不会。为了适应varchar的更新,可以要求页面分割。
其他回答
There are performance benefits, but here is one that has not been mentioned: row migration. With char, you reserve the entire space in advance.So let's says you have a char(1000), and you store 10 characters, you will use up all 1000 charaters of space. In a varchar2(1000), you will only use 10 characters. The problem comes when you modify the data. Let's say you update the column to now contain 900 characters. It is possible that the space to expand the varchar is not available in the current block. In that case, the DB engine must migrate the row to another block, and make a pointer in the original block to the new row in the new block. To read this data, the DB engine will now have to read 2 blocks. No one can equivocally say that varchar or char are better. There is a space for time tradeoff, and consideration of whether the data will be updated, especially if there is a good chance that it will grow.
我认为在你的情况下,可能没有理由不选择Varchar。它为您提供了灵活性,正如许多受访者所提到的,现在的性能是这样的,除非在非常特定的情况下,我们普通人(而不是谷歌DBA)不会注意到差异。
当谈到DB类型时,值得注意的一件有趣的事情是sqlite(一个非常受欢迎的迷你数据库,具有相当令人印象深刻的性能)将所有内容作为字符串放入数据库并动态地输入类型。
我总是使用VarChar,通常使它比我可能迫切需要的要大得多。如你所说,为了安全起见,为什么不买50英镑呢?
当使用varchar值时,SQL Server每行需要额外的2个字节来存储关于该列的一些信息,而如果使用char则不需要 所以除非你
在一些SQL数据库中,为了优化偏移量,VARCHAR将被填充到其最大大小,这是为了加速全表扫描和索引。
因此,与CHAR(200)相比,使用VARCHAR(200)并不会节省任何空间。
我会选择varchar,除非列存储固定的值,如美国州代码-这总是2个字符长,有效的美国州代码列表不经常改变:)。
在其他情况下,甚至像存储哈希密码(固定长度),我会选择varchar。
为什么——char类型的列总是用空格填充,这使得列my_column定义为char(5),值为'ABC'在比较中:
my_column = 'ABC' -- my_column stores 'ABC ' value which is different then 'ABC'
假的。
这个特性可能会在开发过程中导致许多恼人的bug,并使测试更加困难。
推荐文章
- 如何在Ruby On Rails中使用NuoDB手动执行SQL命令
- 查询JSON类型内的数组元素
- 确定记录是否存在的最快方法
- 获得PostgreSQL数据库中当前连接数的正确查询
- 在SQL选择语句Order By 1的目的是什么?
- 我如何循环通过一组记录在SQL Server?
- 如何在SQL Server中一次更改多个列
- 如何从命令行通过mysql运行一个查询?
- 外键约束可能导致循环或多条级联路径?
- 使用LIMIT/OFFSET运行查询,还可以获得总行数
- 当恢复sql时,psql无效命令\N
- 货币应该使用哪种数据类型?
- 如何选择每一行的列值不是独特的
- 如何改变字符集(和排序)在整个数据库?
- mySQL:: insert到表,数据从另一个表?