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
SELECT
statement 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 infooid
orfoosubid
. So the actual simple equivalent is:fiddle
If the table would have
NOT NULL
constraints (incl. the implicit constraint of a PK), there would be no effective difference other than performance.2.
The scope of the subquery in the
IN
expression extends to the main query, wherefoo
is listed in theFROM
clause. Effectively an implicitLATERAL
subquery, where the subquery is executed once for every row in the main query. The manual:See: