How do IMMUTABLE, STABLE and VOLATILE keywords effect behaviour of function?

ぃ、小莉子 提交于 2019-11-26 19:11:35
Erwin Brandstetter

The key word IMMUTABLE is never added automatically by pgAdmin or Postgres. Who ever created or replaced the function did that.

The correct function volatility (read the manual) setting for the given function is VOLATILE, not STABLE - or it wouldn't make sense to use clock_timestamp() which is VOLATILE as opposed to now() or CURRENT_TIMESTAMP, which are defined STABLE: those return the same timestamp within the same transaction, per documentation:

clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command.

The manual warns that function volatility STABLE ...

is inappropriate for AFTER triggers that wish to query rows modified by the current command.

.. because the repeated evaluation of the trigger function for the same row can return different results. So, not STABLE. I don't think the warning is even needed there, since it's rather obvious.

And you ask:

Do you have an idea as to why the function returned correctly five times before sticking on the fifth value when set as IMMUTABLE?

Quoting the Postgres Wiki:

With 9.2, the planner will use specific plans regarding to the parameters sent (the query will be planned at execution), except if the query is executed several times and the planner decides that the generic plan is not too much more expensive than the specific plans.

Bold emphasis mine. Doesn't seem to make sense for an IMMUTABLE function (doesn't do harm either), but maybe the use of a VOLATILE function within still triggers initial re-planing. (The last bit is just my speculation.)
More explanation here:

Aside

trunc() is slightly faster than floor() and does the same here, since positive numbers are guaranteed:

SELECT (trunc(EXTRACT(EPOCH FROM clock_timestamp()) * 10) - 13885344000)::int
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!