Search code examples
databasepostgresqlfunctionplpgsqlreturn-type

Using %rowtype when returning in a PostgreSQL function


If I have a function that returns only one row with some columns from a table. Do I need to add %rowtype in the function return declaration?

CREATE OR REPLACE FUNCTION test(int n)
RETURNS tableName%rowtype AS
$BODY$
DECLARE 
    r tableName%rowtype;    
BEGIN   
    select a,b,c into r from tableName where d=n;
    return r;
$BODY$
END;

Solution

  • About %ROWTYPE

    The %ROWTYPE construct is only good for portability to other RDBMS. Rarely useful, since PL/pgSQL functions are hardly portable to begin with.
    If you are going to use it, it's only meant for variable declaration inside PL/pgSQL function, not to declare the RETURN type, which is part of the outer SQL syntax.

    The manual:

    (Since every table has an associated composite type of the same name, it actually does not matter in PostgreSQL whether you write %ROWTYPE or not. But the form with %ROWTYPE is more portable.)

    Answer

    This would achieve what you seem to be trying:

    CREATE OR REPLACE FUNCTION test_plpgsql(_n int)
      RETURNS tbl
      LANGUAGE plpgsql AS
    $func$
    BEGIN   
      RETURN (SELECT t FROM tbl t where tbl_id = _n);  -- selecting whole row
    END
    $func$;
    

    Call:

    SELECT * FROM test_plpgsql(1);
    

    But if it's as simple as that, use a simpler SQL function to begin with:

    CREATE OR REPLACE FUNCTION test_sql(_n int)
      RETURNS SETOF tbl
      LANGUAGE sql AS
    $func$
       SELECT * FROM tbl WHERE tbl_id = _n;
    $func$;
    

    Call:

    SELECT * FROM test_sql(1);
    

    Your original code example had too many issues. Search for more examples to get a grasp on basic syntax.