Skip to content
Advertisement

Return type of table function with joined result-set

As a follow-up to Parametrized CTE, What would be the following return type for creating the following table function in postgres which returns a result-set containing two joined tables?

WITH info($var1) AS (
    SELECT * FROM sales JOIN product USING (p_id) WHERE website=$var1
) SELECT * FROM info JOIN other USING (id)

For example, converted to a function it might be something along the lines of:

create or replace function select_from_joined_tables(arg text)
returns setof ??? language sql as $$
    select * from sales join product using (p_id) where website = arg
$$;

Advertisement

Answer

You have two options. You can create a custom type containing all the resulting columns. Then the type would be

...
returns setof the_name_of_the_created_type ...
...

Alternatively, you can define the table in a function declaration, e.g.:

...
returns table(id int, website text... etc)
...

Unfortunately, in both cases, a function defined in this way will require some intervention when the structure of the tables is changed.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement