
今天同事问了一个问题,
Oracle中日期类型字段,占用多少空间?
请别琢磨,第一时间你是否能说出答案?
咋一问可能会有些茫然,只要我们动动手,就能得到答案。
首先,Oracle中常见的日期类型字段,可以说有两种,
DATE类型,存储的是“年月日时分秒”。
TIMESTAMP类型,存储的是“年月日时分秒,以及毫秒”。
创建一张测试表,含有DATE和TIMESTAMP两种类型,
SQL create table a (a date, b timestamp); Table created.
插入测试数据,
SQL insert into a values(sysdate, systimestamp); 1 row created.
SQL insert into a values(to_date('2017-01-01','yyyy-mm-dd'), to_date('2017-01-01','yyyy-mm-dd')); 1 row created.
SQL commit; Commit complete.
根据数据字典user_tab_cols看,DATE类型的长度是7byte,TIMESTAMP类型的长度是11byte,
我们使用dump函数,DATE类型的长度len也是7byte,

TIMESTAMP类型的长度len也是11byte,注意第二条记录,由于使用的是to_date,实际存储的是DATE(向TIMESTAMP类型),并不是时间戳TIMESTAMP类型的值。

使用VSIZE函数,也是一样的结论,

是不是没有例外?我们再看一下SYSDATE函数,他应该是一个DATE类型的值,我们注意此处len长度就是8byte,不是DATE类型7byte,而且Typ值是13,DATE类型Typ值是12,TIMESTAMP类型Typ值是180,说明这是不同的类型,

Notice the type for sysdate. It is 13, not 12. 13 is the external DATE datatype. External datatype 13 is an internal c-structure whose length varies depending on how the c-compiler represents the structure. Note that the “Len=” value is 8 and not 7. Type 13 is not a part of the published 3GL interfaces for Oracle and is used for date calculations mainly within PL/SQL operations.
另外,杨长老曾经对于数据类型,写过一些文章,介绍了一些鲜为人知的知识,可以参考《Oracle基本数据类型存储格式浅析(三)——日期类型(三)》(http://blog.itpub.net/4227/viewspace-68517/)。
对于一些疑问,最好的方式就是动手实践,知识点可能很碎,但只要积累起来,一定是笔财富。
如果您觉得本文有帮助,欢迎关注转发:bisal的个人杂货铺,

