I'm learning how to write functions in Postgresql. I've defined a function called _tmp_myfunction() which takes in an id and returns a table (I also define a table object type called _tmp_mytable)
-- create object type to be returned
CREATE TYPE _tmp_mytable AS (
id integer,
cost double precision
);
-- create function which returns query
CREATE OR REPLACE FUNCTION _tmp_myfunction(
id integer
)
RETURNS SETOF _tmp_mytable AS $$
BEGIN
RETURN QUERY
SELECT
sales.gid,
cost
FROM
sales
WHERE
id = sales.gid;
END;
$$ LANGUAGE plpgsql;
This works fine when I use one id and call it using the following approach:
SELECT * FROM _tmp_myfunction(402);

What I would like to be able to do is to call it, but to use a column of values instead of just one value. However, if I use the following approach I end up with all values of the table in one column, separated by commas:
-- call function using all values in a column
SELECT _tmp_myfunction(t.id)
FROM transactions as t;

I understand that I can get the same result if I use SELECT _tmp_myfunction(402); instead of SELECT * FROM _tmp_myfunction(402); but I don't know how to construct my function in such a way that I do not get composite values when I pass in a column of values.
SELECT, the behaviour can be truly bizarre. It's a legacy PostgreSQL specific hack that should be abandoned as soon as PostgreSQL 9.3'sLATERALis available for use. For just how weird, compareSELECT generate_series(1,3), generate_series(1,3);toSELECT generate_series(1,3), generate_series(1,4);. The 1st returns three rows, pairs of results in order. The second returns twelve rows, all possible pairings of results, like a cross product.