How to display column headers returned by PostgreSQL function?
Asked Answered
I

3

8

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, [email protected], "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          [email protected]   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.

Immiscible answered 14/6, 2017 at 3:5 Comment(0)
P
3

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    | [email protected] | 2017-06-13 12:00:00-04
Perilymph answered 14/6, 2017 at 3:26 Comment(0)
C
6

You need to format PostgreSQL to show the colum headers; Set it with:

\t

this can be seen in PSQL help

\?

Constitutional answered 27/5, 2022 at 1:2 Comment(1)
This one is confusing because you get the message tuples only is on or tuples only is off. Tuples as in rows of values only, without the column headers.Illampu
P
3

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    | [email protected] | 2017-06-13 12:00:00-04
Perilymph answered 14/6, 2017 at 3:26 Comment(0)
H
0

You can use "as" in your query. Select Id as id, username as username....

Hesperian answered 14/6, 2017 at 3:13 Comment(1)
The 'as' works for me : SELECT ar.invnumber as "Inv No", ar.amount as "Inv Total", ar.transdate as "Inv Date", customer.name as "Customer", acc_trans.amount as "Amount Recd", acc_trans.transdate as "Date Recd"Greywacke

© 2022 - 2024 — McMap. All rights reserved.