Search code examples
sqlpostgresqlunion

PostgrSQL UNION by key


Can't come up with easy solution how to union tables with same columns but from second table add only rows which are present in first table.

t1:

id A B C
1 xx r g
2 cc r g
5 d g e

t2:

id A B C
101 jyj u j
5 y jku u
12 y r j

desired t1 union t2:

id A B C
1 xx r g
2 cc r g
5 d g e
5 y jku u

Appreciate any help.


Solution

  • We can use an IN clause and say the id of table 2 must appear in table 1:

    SELECT id, A, B, C
    FROM t1
    UNION ALL
    SELECT id, A, B, C
    FROM t2
    WHERE t2.id IN (SELECT id FROM t1);
    

    Try out: db<>fiddle