Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9057519
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T14:28:38+00:00 2026-06-16T14:28:38+00:00

I have a PostgreSQL function (or table) which gives me the following output: Sl.no

  • 0

I have a PostgreSQL function (or table) which gives me the following output:

Sl.no    username    Designation    salary   etc..
 1        A           XYZ            10000    ...
 2        B           RTS            50000    ...
 3        C           QWE            20000    ...
 4        D           HGD            34343    ...

Now I want the Output as below:

Sl.no            1       2        3       4       ...
 Username        A       B        C       D       ...
 Designation     XYZ     RTS      QWE     HGD     ...
 Salary          10000   50000    20000   34343   ...

How to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T14:28:39+00:00Added an answer on June 16, 2026 at 2:28 pm

    Basing my answer on a table of the form:

    CREATE TABLE tbl (
      sl_no int
    , username text
    , designation text
    , salary int
    );
    

    Each row results in a new column to return. With a dynamic return type like this, it’s hardly possible to make this completely dynamic with a single call to the database. Demonstrating solutions with two steps:

    1. Generate query
    2. Execute generated query

    Generally, this is limited by the maximum number of columns a table can hold. So not an option for tables with more than 1600 rows (or fewer). Details:

    • What is the maximum number of columns in a PostgreSQL select query

    Postgres 9.4+

    Dynamic solution with crosstab()

    Use the first one if you can. Beats the rest.

    SELECT 'SELECT *
    FROM   crosstab(
           $ct$SELECT u.attnum, t.rn, u.val
            FROM  (SELECT row_number() OVER () AS rn, * FROM '
                                  || attrelid::regclass || ') t
                 , unnest(ARRAY[' || string_agg(quote_ident(attname)
                                  || '::text', ',') || '])
                     WITH ORDINALITY u(val, attnum)
            ORDER  BY 1, 2$ct$
       ) t (attnum bigint, '
         || (SELECT string_agg('r'|| rn ||' text', ', ')
             FROM  (SELECT row_number() OVER () AS rn FROM tbl) t)
         || ')' AS sql
    FROM   pg_attribute
    WHERE  attrelid = 'tbl'::regclass
    AND    attnum > 0
    AND    NOT attisdropped
    GROUP  BY attrelid;

    Operating with attnum instead of actual column names. Simpler and faster. Join the result to pg_attribute once more or integrate column names like in the pg 9.3 example.
    Generates a query of the form:

    SELECT *
    FROM   crosstab(
       $ct$
       SELECT u.attnum, t.rn, u.val
       FROM  (SELECT row_number() OVER () AS rn, * FROM tbl) t
           , unnest(ARRAY[sl_no::text,username::text,designation::text,salary::text]) WITH ORDINALITY u(val, attnum)
       ORDER  BY 1, 2$ct$
       ) t (attnum bigint, r1 text, r2 text, r3 text, r4 text);
    

    This uses a whole range of advanced features. Just too much to explain.

    Simple solution with unnest()

    One unnest() can now take multiple arrays to unnest in parallel.

    SELECT 'SELECT * FROM unnest(
      ''{sl_no, username, designation, salary}''::text[]
    , ' || string_agg(quote_literal(ARRAY[sl_no::text, username::text, designation::text, salary::text])
                  || '::text[]', E'\n, ')
        || E') \n AS t(col,' || string_agg('row' || sl_no, ',') || ')' AS sql
    FROM   tbl;
    

    Result:

    SELECT * FROM unnest(
     '{sl_no, username, designation, salary}'::text[]
    ,'{10,Joe,Music,1234}'::text[]
    ,'{11,Bob,Movie,2345}'::text[]
    ,'{12,Dave,Theatre,2356}'::text[])
     AS t(col,row1,row2,row3,row4);
    

    db<>fiddle here
    Old sqlfiddle

    Postgres 9.3 or older

    Dynamic solution with crosstab()

    • Completely dynamic, works for any table. Provide the table name in two places:
    SELECT 'SELECT *
    FROM   crosstab(
           ''SELECT unnest(''' || quote_literal(array_agg(attname))
                               || '''::text[]) AS col
                 , row_number() OVER ()
                 , unnest(ARRAY[' || string_agg(quote_ident(attname)
                                  || '::text', ',') || ']) AS val
            FROM   ' || attrelid::regclass || '
            ORDER  BY generate_series(1,' || count(*) || '), 2''
       ) t (col text, '
         || (SELECT string_agg('r'|| rn ||' text', ',')
             FROM (SELECT row_number() OVER () AS rn FROM tbl) t)
         || ')' AS sql
    FROM   pg_attribute
    WHERE  attrelid = 'tbl'::regclass
    AND    attnum > 0
    AND    NOT attisdropped
    GROUP  BY attrelid;

    Could be wrapped into a function with a single parameter …
    Generates a query of the form:

    SELECT *
    FROM   crosstab(
           'SELECT unnest(''{sl_no,username,designation,salary}''::text[]) AS col
                 , row_number() OVER ()
                 , unnest(ARRAY[sl_no::text,username::text,designation::text,salary::text]) AS val
            FROM   tbl
            ORDER  BY generate_series(1,4), 2'
       ) t (col text, r1 text,r2 text,r3 text,r4 text);
    

    Produces the desired result:

    col         r1    r2      r3     r4
    -----------------------------------
    sl_no       1      2      3      4
    username    A      B      C      D
    designation XYZ    RTS    QWE    HGD
    salary      10000  50000  20000  34343
    

    Simple solution with unnest()

    SELECT 'SELECT unnest(''{sl_no, username, designation, salary}''::text[] AS col)
         , ' || string_agg('unnest('
                        || quote_literal(ARRAY[sl_no::text, username::text, designation::text, salary::text])
                        || '::text[]) AS row' || sl_no, E'\n     , ') AS sql
    FROM   tbl;
    
    • Slow for tables with more than a couple of columns.

    Generates a query of the form:

    SELECT unnest('{sl_no, username, designation, salary}'::text[]) AS col
         , unnest('{10,Joe,Music,1234}'::text[]) AS row1
         , unnest('{11,Bob,Movie,2345}'::text[]) AS row2
         , unnest('{12,Dave,Theatre,2356}'::text[]) AS row3
         , unnest('{4,D,HGD,34343}'::text[]) AS row4
    

    Same result.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a plpgsql function in PostgreSQL 9.2 which returns a table. The function
I have postgresql (in perlu) function getTravelTime(integer, timestamp), which tries to select data for
I have an PostgreSQL Function which returns me an XML where the whole infos
I have a large PostgreSQL table which I access through Django. Because Django's ORM
I have a temporary table in a PostgreSQL function and I want to insert
I have a postgresql database and am using it for a project which handles
I have one postgresql table where I store some stories from different sites. At
I have the following PostgreSQL query: INSERT INTO persoane_alocate(pa_id_pj,pa_id_corespondent_persoana,pa_procentaj,pa_tip_persoana,pa_data_inceput,pa_data_sfarsit,pa_afisare_in_monitor,audit_data_modificarii,audit_id_utilizator) VALUES ('670', '534', '0', '1',
I have a table that has a TEXT column which contains hexadecimal numbers. I
I have created a table in postgresql 9 create table stillbirth(id serial primary key,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.