Giovanna
Giovanna

Reputation: 41

How to insert null value when doing left join in SQL

I have these 2 table (each element is in column):

TABLE A: 
ID  1  2  3 4 5
TD  20 10 0 1 7

TABLE B:
ID  2  3 
TD  40 30 

I want to do a LEFT JOIN to obtain a FINAL_TABLE in which I have all the ID od TABLE A and the one of table B in common with A. I want also that in case there is ID in TABLE A and not in TABLE B (ex. ID 1,4,5), in the FINAL_TABLE I will show NULL at that ID. The FINAL_TABLE should be (see all in column):

ID  1    2  3  4    5
TDA 20   10 0  1    7
TDB NULL 40 30 NULL NULL

How can I achieve that?

Upvotes: 0

Views: 1873

Answers (2)

Aritra Bhattacharya
Aritra Bhattacharya

Reputation: 780

I think this should work. Could you please try this once.

    INSERT INTO FINAL_TABLE
    (
        ID,
        tdA,
        tdB
    )
    SELECT 
        A.ID,
        A.td,
        B.td
    FROM
        TABLEA 
    LEFT OUTER JOIN TABLEB ON (A.ID=B.ID)
    GROUP BY
        A.ID,
        A.td,
        B.td
    ;

Upvotes: 0

jarlh
jarlh

Reputation: 44796

Not quite sure if this is what you ask for, but perhaps you just want to add one result to another?

select 'TDA', col1, col2, col3, col4, col5 from tableA
UNION ALL
select 'TDB', null, col1, col2, null, null from tableB

Upvotes: 1

Related Questions