Aman
Aman

Reputation: 680

full outer join 3 tables with matching index in Postgre SQL

I have an SQL query

SELECT * FROM A FULL OUTER JOIN B ON A.z = B.z WHERE A.z = 1 OR B.z = 1

where A.z and B.z are primary keys.

The purpose is to do a full outer join on two tables whilst their primary keys match a given value - so that only one row is returned.

But I got confused on how to extend it to 3 or more tables. The restriction that their primary keys match a given index so that only one row is return in total remains. How do you do it?

Upvotes: 3

Views: 7847

Answers (1)

Benoit
Benoit

Reputation: 79233

First, note that in the provided query, the FULL OUTER JOIN that you request could be rewritten as:

         SELECT *
           FROM (SELECT * FROM A WHERE z = 1) A
FULL OUTER JOIN (SELECT * FROM B WHERE z = 1) B ON A.z = B.z

which makes (IMO) more clear what the data sources are and what the join condition is. For a moment, with your WHERE condition, I had the feeling that you wanted actually an INNER JOIN.

With this you can extend more easily probably:

         SELECT *
           FROM (SELECT * FROM A WHERE z = 1) A
FULL OUTER JOIN (SELECT * FROM B WHERE z = 1) B ON A.z = B.z
FULL OUTER JOIN (SELECT * FROM C WHERE z = 1) C ON COALESCE(A.z,B.z) = C.z
FULL OUTER JOIN (SELECT * FROM D WHERE z = 1) D ON COALESCE(A.z,B.z,C.z) = D.z

Upvotes: 16

Related Questions