Search code examples
sqlpostgresqlset-returning-functions

How to display column headers returned by PostgreSQL function?


I have the following PostgreSQL function which returns multiple columns from a table:

CREATE OR REPLACE FUNCTION userbyid(id integer)
RETURNS TABLE(id int, username character varying(30), email character varying(254), last_login timestamp with time zone) AS
$$
SELECT
    id,
    username,
    email,
    last_login
FROM
    auth_user
WHERE
    id = $1;
$$
LANGUAGE 'sql';

The result it returns looks like this:

                        userbyid
--------------------------------------------------------------
(2, smith, smith@example.com, "2017-06-04 19:47:49.472259+00")

Is it possible to display the output with the correct column headers, something like this:

id         username       email               last_login
--------------------------------------------------------------
2          smith          smith@example.com   2017-06-04

I'm looking at the CREATE FUNCTION document page and it isn't clear how to do this. I've also searched online and haven't seen an article that discusses this.


Solution

  • Use your set returning function in the FROM clause

    SELECT * FROM userbyid(1);
    

    as opposed to

    SELECT userbyid(1);
    

    Here is dbfiddle demo

    Sample output:

     id | username |       email       |       last_login
    ----+----------+-------------------+------------------------
      1 | user1    | user1@example.com | 2017-06-13 12:00:00-04