You can create a TYPE
or use the type of an existing table. Then use RETURNS SETOF my_type
.
But for a row type you only need in a single function it's more convenient to just use RETURNS TABLE (...)
- possibly in combination with RETURN QUERY
:
CREATE OR REPLACE FUNCTION my_function(user_id bigint)
RETURNS TABLE(field1 int, field2 text) AS -- replace with actual types!
$func$
BEGIN
RETURN TABLE
SELECT t1.field1, t2.field2 -- table-qualify to avoid naming conflict
FROM table1 t1
JOIN table2 t2 ON ...
... ;
-- if var1 is not null ...
IF NOT FOUND THEN
-- If nothing was found, you can ...
-- RAISE EXCEPTION 'foo!' -- to raise an exception. Or ...
-- RETURN QUERY SELECT 1, 'foo'; -- return a "default" row ...
END IF;
END
$func$ LANGUAGE plpgsql;
Search for those key words in the plpgsql tag. There are many examples.