Is it possible to use a stable function in an index in Postgres?

故事扮演 提交于 2019-12-10 18:29:35

问题


I've been working on a project at work and have come to the realization that I must invoke a function in several of the queries' WHERE clauses. The performance isn't terrible exactly, but I would love to improve it. So I looked at the docs for indexes which mentioned that:

An index field can be an expression computed from the values of one or more columns of the table row.

Awesome. So I tried creating an index:

CREATE INDEX idx_foo ON foo_table (stable_function(foo_column));

And received an error:

ERROR: functions in index expression must be marked IMMUTABLE

So then I read about Function Volatility Categories which had this to say about stable volatility:

In particular, it is safe to use an expression containing such a function in an index scan condition.

Based on the phrasing "index scan condition" I'm guessing it doesn't mean an actual index. So what does it mean? Is it possible to utilize a stable function in an index? Or do we have to go all the way and ensure this would work as an immutable function?

We're using Postgres v9.0.1.


回答1:


An "index scan condition" is a search condition, and can use a volatile function, which will be called for each row processed. An index definition can only use a function if it is immutable -- that is, that function will always return the same value when called with any given set of arguments, and has no user-visible side effects. If you think about it a little, you should be able to see what kind of trouble you could get into if the function might return a different value than what it did when the index entry was created.

You might be tempted to lie to the database and declare a function as immutable which isn't really; but if you do, the database will probably do surprising things that you would rather it didn't.

9.0.1 has bugs for which fixes are available. Please upgrade to 9.0.somethingrecent.

http://www.postgresql.org/support/versioning/



来源:https://stackoverflow.com/questions/10390777/is-it-possible-to-use-a-stable-function-in-an-index-in-postgres

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