Check out "iscacheable" ("iscachable"???) in the PG documentation. This avoids the problem. Ideally PL/pgSQL would recognize invariants when compiling and set this for you but it's not likely to happen for a long time ... meanwhile you're free to give PG hints.