Skip to content
Advertisement

Doing a union on two tables, but renaming columns that may have the same name in postgres and dropping others

I am doing a union on two tables that have some of the same column names. So, say they look something like this:

table1
=========
_id
fk_id
name
details
createdAt
updatedAt

table2
=========
_id
fk_id
name
age
details
createdAt
updatedAt

Here is what I am currently doing:

SELECT * FROM "table1"
    JOIN table2
    ON table1."fk_id"=table2."fk_id";

Currently I obviously get repeated columns. So here is what I want to do:

1- The table2’s columns name and details, I would like to rename to t1_name and t2_details respectively

2- I would like to drop table2’s _id, fk_id, createdAt and updatedAt properties. How do I do that?

Advertisement

Answer

Just enumerate the columns that you want to retain, and alias them as needed:

select
    t1._id,
    t1.fk_id,
    t1.name t1_name,
    t1.details t1_details,
    t1.createdAt,
    t1.updatedAt,
    t2.name t2_name,
    t2.age,
    t2.details t2_details
from table1 t1
inner join table2 t2 on t1.fk_id = t2.fk_id
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement