Skip to content
Advertisement

Creating a key value pair table

I have a table with 32 columns whose primary key is play_id and my goal is to create a key value pair table where the output would look like this:

where all the entries in field_name are columns from the original table (besides play_id). So there would be 31 appearances of play_id_1 in this new table. I want the new primary key for this table to be (play_id, field_name). There’s a long way of doing it where I can query for play_id and each column and union everything together, but I want to find a more elegant solution.

Advertisement

Answer

You can use a lateral join for that. But you will need to cast all values to text.

Another option is to convert the row to a JSON value and then unnest that json:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement