In today’s article, I will be explaining what Outer Join is and its types in PostgreSQL.
It is a join type that contains several join types in OUTER JOIN.
Retrieves common records by using interrelated columns between tables such as INNER JOIN.
Its difference from INNER JOIN may vary depending on the outer join type used instead of fetching common columns.
The outer join is divided into three:
-Left Join
-Right Join
-Full Outer Join
You cannot use OUTER JOIN alone by typing OUTER JOIN.
You can use it as LEFT OUTER JOIN, RIGHT OUTER JOIN or FULL OUTER JOIN.
Left Outer Join:
It is called LEFT OUTER JOIN or LEFT JOIN, as the name suggests, it performs the join operation based on the left table.
The records in the first table are listed completely, then if the record in the first table does not exist in the second table, its value in the second table returns empty.
For example, in the example we did in my INNER JOIN article, we entered Gaziantep in the sehirler table, but since we did not enter a record about Gaziantep in the MeshurYiyecek table, it was not listed in the INNER JOIN.
Let’s run the same query by typing LEFT JOIN or LEFT OUTER JOIN where it says INNER JOIN.
1 |
SELECT s.sehirismi,my.yiyecekismi FROM sehirler as s LEFT JOIN meshuryiyecekler as my ON s.id=my.sehirid; |
As you can see above, the Gaziantep value is returned and the YiyecekIsmi column in the MeshurYiyecek table is null because there is no record.
You can meet your different needs by filtering this query in the ‘where’ condition.
For example, let’s enter the sehirismi, but if we want to list the records that do not have famous food related to this city or that have not been entered, we can write the following query.
1 |
SELECT s.sehirismi,my.yiyecekismi FROM sehirler as s LEFT JOIN meshuryiyecekler as my ON s.id=my.sehirid WHERE my.sehirid is null; |
Right Outer Join:
It is called RIGHT OUTER JOIN or RIGHT JOIN, as the name suggests, it performs the join operation based on the right table.
It returns all records belonging to table B in the picture above.
In the picture above, only the ones in table B will not return the values in table A.
1 |
SELECT s.sehirismi,my.yiyecekismi FROM sehirler as s RIGHT JOIN meshuryiyecekler as my ON s.id=my.sehirid WHERE s.id is null; |