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

  • Home
  • SEARCH
  • 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 6130771
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T16:53:49+00:00 2026-05-23T16:53:49+00:00

Consider the example below where I have a Person table containing person records and

  • 0

Consider the example below where I have a Person table containing person records and a PersonAttribute table which contains optional attributes linked to a person:

Table: Person

ID    Name
1     Joe Bloggs
2     Jane Doe

Table PersonAttribute

PersonId  Key         Value
1         Age         27            
2         HairColor   Brown

How would I write a query that returns all people with the attributes as if they were columns? The resultset I require is:

ID    Name        Age    HairColor
1     Joe Bloggs  27     
2     Jane Doe           Brown

So essentially I need to write a query that gets all Person Records with all unique Attribute Keys transposed as columns with the value for each person record.

Note that the primary key on the PersonAttribute table is PersonID and Key combined so we wont have duplicate entries for a specific key and person.

Obviously I could add the Age and HairColor as fields in the Person table and not use the PersonAttribute table at all, but this is just an example to illustrate the problem. In reality I have a huge number of custom attributes that vary wildly for different person records so it is not practical to do it that way.

  • 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-05-23T16:53:50+00:00Added an answer on May 23, 2026 at 4:53 pm

    I can’t speak about MySQL, but in PostgreSQL you could use crosstab function from tablefunc module:

    CREATE OR REPLACE VIEW PersonAttributePivot AS
        SELECT PersonId AS ID, Age, HairColor
        FROM crosstab
        (
           'SELECT PersonId, Key, Value FROM PersonAttribute',
           'SELECT DISTINCT Key FROM PersonAttribute ORDER BY Key'
        )
        AS
        (
            PersonId integer,
            Age text,
            HairColor text
        );
    

    Join query:

    SELECT id, name, age, haircolor
    FROM Person JOIN PersonAttributePivot USING(id)
    ORDER BY id;
    

    Wanted result:

     id |    name    | age | haircolor 
    ----+------------+-----+-----------
      1 | Joe Bloggs | 27  | 
      2 | Jane Doe   |     | Brown
    (2 rows)
    

    As you see I put explicit list of columns in PersonAttributePivot view. I don’t know any “automatic-pivot” creation way with implicit column list.

    EDIT:

    For huge column list (assuming always text type) as a workaround I see such little modified approach:

    Dynamic type creation (here trivially Java based):

    Class.forName("org.postgresql.Driver");
    Connection c =
            DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "12345");
    Statement s = c.createStatement();
    ResultSet rs = s.executeQuery("SELECT DISTINCT Key FROM PersonAttribute ORDER BY Key");
    List<String> columns = new ArrayList<String>();
    
    while (rs.next())
        columns.add(rs.getString(1));
    
    System.out.println("CREATE TYPE PersonAttributePivotType AS (");
    System.out.println("\tPersonId integer,");
    for (int i = 0; i < columns.size(); ++i)
    {
        System.out.print("\t" + columns.get(i) + " text");
        if (i != columns.size() - 1)
            System.out.print(",");
        System.out.println();
    }
    System.out.println(");");
    

    Result:

    CREATE TYPE PersonAttributePivotType AS (
        PersonId integer,
        Age text,
        HairColor text
    );
    

    Function wrapper:

    CREATE OR REPLACE FUNCTION crosstabPersonAttribute(text, text)
        RETURNS setof PersonAttributePivotType
        AS '$libdir/tablefunc','crosstab_hash' LANGUAGE C STABLE STRICT;
    

    Automatic view creation:

    CREATE OR REPLACE VIEW PersonAttributePivot AS
        SELECT * FROM crosstabPersonAttribute
        (
           'SELECT PersonId, Key, Value FROM PersonAttribute',
           'SELECT DISTINCT Key FROM PersonAttribute ORDER BY Key'
        );
    

    Result:

    TABLE PersonAttributePivot;
     personid | age | haircolor
    ----------+-----+-----------
            1 | 27  |
            2 |     | Brown
    (2 rows)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's consider the below example. There, I have: target MAIN calls target t and
Suppose that I have a database query which looks like below - select name,
I have a table like below Consider the table id=testtable, and there is no
Consider the code below (which has been simplified). I have a service class that
Consider I have a table, like below, that I am trying to populate with
Consider this example table (assuming SQL Server 2005): create table product_bill_of_materials ( parent_product_id int
Consider this example (typical in OOP books): I have an Animal class, where each
I have an array filled with instances of a custom class which contains two
Consider the table of events below. The OrderID field is a foreign key to
The question is pretty straight forward. For clarity, consider the example below: // Note

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.