Postgres SQL - Concatenate Tables with different columns

Viewed 135

I've looked up ways to solve my problem here on SO and other sources, but nothing i have tried worked, so here i am.

I need to concatenate two tables with different columns, as it follows:

(data is just a represetantion, not my actual data and i'm using Postgres SQL)

Table_1:

name   price  id  location
test   1.0     7  Canada

Table_2

name     store         sale  price  location
testing  local_store   54    2.0      US

My actual tables have over 30 rows each, but the resulting table i need would look like this:

Table_concat:

name     price  store        sale   id    location   
test     1.0    null         null   7     Canada  (row from Table_1)
testing  2.0    local_store  54     null  US      (row from Table_2)

Basically, i need to put one table on top of another and when the columns do not match, a null value should apear. Can anyone help me? I can provide further explanation if necessary.

1 Answers

Try this query:

SELECT 
  name, price, null AS store, null AS sale, id, location
FROM Table_1

UNION 

SELECT 
  name, price, store, sale, null AS id, location
FROM Table_2
Related