SQL Joins
SQL Joins
the related columns. The related columns are typically the primary key column(s) of
the first table and foreign key column(s) of the second table.
Oracle supports inner join, left join, right join, full outer join and cross join.
We will create two new tables with the same structure for the demonstration:
);
);
The following statement joins the left table to the right table using the values in
the color column:
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a
As can be seen clearly from the result, the inner join returns rows from the left table
that match with the rows from the right table.
The following Venn diagram illustrates an inner join when combining two result sets:
The following statement joins the left table with the right table using a left join (or a
left outer join):
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a
The left join returns all rows from the left table with the matching rows if available
from the right table. If there is no matching row found from the right table, the left
join will have null values for the columns of the right table:
Sometimes, you want to get only rows from the left table that do not exist in the right
table. To achieve this, you use the left join and a WHERE clause to exclude the rows
from the right table.
For example, the following statement shows colors that only available in
the palette_a but not palette_b:
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a
The following Venn diagram illustrates the left join with the exclusion of rows from
the right table:
Oracle right join
The right join or right outer join is a reversed version of the left join. The right join
makes a result set that contains all rows from the right table with the matching rows
from the left table. If there is no match, the left side will have nulls.
The following example use right join to join the left table to the right table:
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a
Oracle full outer join or full join returns a result set that contains all rows from both
left and right tables, with the matching rows from both sides where available. If there
is no match, the missing side will have nulls.
The following example shows the full outer join of the left and right tables:
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a
The following picture illustrates the result set of the full outer join:
To get a set of rows that are unique from the left and right tales, you perform the
same full join and then exclude the rows that you don’t want from both sides using
a WHERE clause as follows:
SELECT
a.id id_a,
a.color color_a,
b.id id_b,
b.color color_b
FROM
palette_a a