IMMUTABLE | STABLE | VOLATILE
分别代表,非常稳定,稳定,不稳定。
稳定,函数不可以修改数据库的数据,同一个QUERY中,如果需要返回该函数的结果,那么将合并多次运算为一次这个函数(后面会有例子)。另外,只有stable和immutable的函数才可以被执行计划选择作为索引的比较条件。(因为索引比较时,被比较的值只运算一次.这个就需要stable和immutable了)
在创建函数时,必须严格的定义稳定性状态,否则可能导致意想不到的后果,因为PLAN CACHE以及prepared statement等原因.
函数索引必须是immutable的 .
另外稳定性选项还影响了对数据的可视特性,如
STABLEandIMMUTABLEfunctions use a snapshot established as of the start of the calling query,whereasVOLATILEfunctions obtain a fresh snapshot at the start of each query they execute.
实例:
下面来用几个时间函数来测试一下:
proname | provolatile pronargs----------------------------------------+-------------+----------timenow s 0timeofday v now transaction_timestamp statement_timestamp clock_timestamp 0
其中
clock_timestamp是voatile的.now是stable的。
digoal => create table tbl_time ( id int , row_time timestamp without time zone stat_time timestamp without time zone );CREATE TABLEdigoal insert into tbl_time select generate_series ( 1 10000 ),0)">clock_timestamp (),0)">now ();INSERT 0 10000digoal=> select count(*),count(distinct row_timedistinct stat_time)from tbl_time;count count count-------+-------+-------10000 1(1 row)