我应该在执行查询的函数中使用 STABLE 还是 VOLATILE?

Should i use STABLE or VOLATILE in a function that performs a query?

我正在尝试对检查计数是否大于或等于 2 的特定函数使用正确的修饰符,但我不确定要使用哪个,函数如下:

CREATE FUNCTION check_table_ids()
RETURNS trigger AS
$$
DECLARE
   counter integer := (SELECT count(*) FROM table WHERE fk_id = NEW.fk_id AND status <> 'CANCELED');
BEGIN
   IF counter >= 2 THEN
       RAISE EXCEPTION 'The number of entries for "%" is greater or equal than 2', NEW.fk_id;
   END IF;

   RETURN NEW;
END;
$$ LANGUAGE plpgsql VOLATILE;

顺便说一下,这个函数将在插入时由触发器调用。

根据手册(https://www.postgresql.org/docs/current/static/sql-createfunction.html

STABLE indicates that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same argument values, but that its result could change across SQL statements.

因此,如果您修改数据库或在不更改数据库的情况下给出不同的结果,则使用 VOLATILE,否则使用 STABLE

对于你问题中的代码 STABLE 应该没问题。

这由触发器调用这一事实并没有什么不同,因为它是您声明为 STABLE 的函数的内容,而不是它的用法。