我意识到,如果我的所有值都是固定宽度的,建议使用CHAR。但是,那又怎样?为了安全起见,为什么不为所有文本字段选择VARCHAR呢?
当前回答
早期性能优化和使用最佳实践类型的规则之间存在差异。如果创建的新表中总是有固定长度的字段,那么使用CHAR是有意义的,在这种情况下应该使用它。这不是早期优化,而是实现经验法则(或最佳实践)。
即-如果你有一个2字母的状态字段,使用CHAR(2)。如果您有一个包含实际州名的字段,请使用VARCHAR。
其他回答
碎片。Char会保留空间,而VarChar则不会。为了适应varchar的更新,可以要求页面分割。
我会选择varchar,除非列存储固定的值,如美国州代码-这总是2个字符长,有效的美国州代码列表不经常改变:)。
在其他情况下,甚至像存储哈希密码(固定长度),我会选择varchar。
为什么——char类型的列总是用空格填充,这使得列my_column定义为char(5),值为'ABC'在比较中:
my_column = 'ABC' -- my_column stores 'ABC ' value which is different then 'ABC'
假的。
这个特性可能会在开发过程中导致许多恼人的bug,并使测试更加困难。
Char更快一点,所以如果你知道一个列有一定的长度,就使用Char。例如,存储(M)ale/(F)emale/(U)nknown表示性别,或者存储2个字符表示美国的一个州。
在计算列值实际所需的大小和为Varchar分配空间时,会有一些小的处理开销,因此如果您确实确定值总是多长,那么最好使用Char并避免命中。
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.
推荐文章
- GROUP BY with MAX(DATE)
- 删除id与其他表不匹配的sql行
- 等价的限制和偏移SQL Server?
- 为什么我不能在DELETE语句中使用别名?
- 在SQL Server Management Studio中保存带有标题的结果
- "where 1=1"语句
- 如何选择一个记录和更新它,与一个单一的查询集在Django?
- 多语句表值函数vs内联表值函数
- 如何从Oracle的表中获取列名?
- NOLOCK提示在SELECT语句中的作用
- SQL OVER()子句-它什么时候有用,为什么有用?
- 如果字段在MySQL中为空,则返回0
- 我如何使用ROW_NUMBER()?
- SQL或者TSQL是图灵完备的吗?
- 如何检查表上持有哪些锁