Skip to content
Advertisement

Arranging VARCHAR data into Columns in SQL

My data is in a SQL table in the following format (I have about 20 different answers per user_id):

I would like to create a view in PostgreSQL where all the data is shown according to User ID

Thank you!

Advertisement

Answer

It is great example of not relational data (the semantic depends on row number), although the data are saved in relational database. You cannot to make relational data from not relational inside relational database. There is not any mechanism how to do this transformation safely. Theoretically, if physical order of your data is same like in your picture, then you can write queries (but you should not to use ORDER BY clause, because it can change order, because your data doesn’t hold necessary data for correct ordering):

You need function:

This function can add missing order information to relation. It is pretty ugly solution, but your input data are in very unhappy format, and there is not possible any clean solution (based on relational algebra):

Now, the transformation to the requested format is easy (search pivoting):

The main problem is in format of your input data. It can be good enough for file and application processing, but are terrible bad for storing (and processing) in relation database. The relation (or the table) is heap (not file).

With knowledge of Postgres’s internals, you can ensure expected order although you use some relational operations. You can use internal implicit column ctid. ctid is an unique address of row. This will not work on other databases, and it will not work on older Postgres releases:

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