I have some questions regarding the example for table functions in PostgreSQL manual:
CREATE TABLE foo (fooid int, foosubid int, fooname text);
CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$
SELECT * FROM foo WHERE fooid = $1;
$$ LANGUAGE SQL;
SELECT * FROM foo
WHERE foosubid IN (
SELECT foosubid
FROM getfoo(foo.fooid) z
WHERE z.fooid = foo.fooid
);
How is this particular nested
SELECTstatement different, including subtle things, fromSELECT * FROM foo? How is this particular statement useful?How is
getfoo(foo.fooid)able to know the value offoo.fooid? Does a function always iterate through all values when we pass in an argument liketable.column?
1.
The query's is useless - other than to demonstrate syntax and functionality. It burns down to just
SELECT * FROM foo- except that it eliminates rows with null values infooidorfoosubid. So the actual simple equivalent is:fiddle
If the table would have
NOT NULLconstraints (incl. the implicit constraint of a PK), there would be no effective difference other than performance.2.
The scope of the subquery in the
INexpression extends to the main query, wherefoois listed in theFROMclause. Effectively an implicitLATERALsubquery, where the subquery is executed once for every row in the main query. The manual:See: