Hi I have some questions regarding table functions in PostgreSQL
From https://www.postgresql.org/docs/16/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS
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
?
Thanks
2
Answers
The query does nothing useful and returns all table rows. It is just an example.
The function will be called for each row of the table. You can use
EXPLAIN
to see how PostgreSQL processes the query.1.
The query’s is useless – other than to demonstrate syntax and functionality. It query 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: