Skip to content
Advertisement

Getting Foreign Keys as separate columns

i’m not really much of an expert when it comes to databases and i was wondering if it’s possible to do something which might be a little weird

I’m having a simple table called options which has 3 columns : id(PK), user_id(FK), option

The table looks like this:

enter image description here

Is is possible to write a query that breaks the option column into multiple columns for each user_id?For example, looking at the photo it would be something like this:

I need to get the data like this because it would be easier to export it in a text file using java

Advertisement

Answer

Yes, you can do that with an extension called tablefunc.

Documentation https://www.postgresql.org/docs/10/tablefunc.html

Example

List out extensions we currently have:

Add tablefunc extension

Great, now the extension is available. Let’s write the query

Query

Result

Hope this helps.

Limitation

The limitation is that it does not create columns automatically. However, you can write a stored function that reads the maximum number of columns to generate and dynamically creates a query, and executes it.

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