SQL Joining Tables

All the queries you've seen so far have been concentrated on a single table. But in real life situation you often need to query two or more tables at time and bring a combined result set. This is technically referred to as a join, since it involves joining different tables, based on a common field between them (the foreign key) to create new views of the data.

To understand this easily, let's look at the following employees and departments tables. Here, the dept_id column of the employees table is the foreign key to the departments table. Therefore, these two tables can be joined to get the combined data.

Types of Joins

When you join tables, the type of join that you create in your query affects the rows that appear in the result set. You can create the following types of joins:

Inner join

A join that returns only those rows that have a match in both joined tables. For example, you can join the employees and departments tables to create a result set that shows the department name for each employee. In an inner join, employees for which there is no department information are not included in the result set, nor are departments with no employees.

Outer join

Outer joins are an extension to inner joins. An outer join returns the rows even if they don't have related rows in the joined table. There are three types of outer joins: left outer join (or left join), right outer join (or right join), and full outer join (or full join).

Cross join

Cross joins are joins without a join condition. Each row of one table is combined with each row of another table. This type of result set is called a Cartesian product or cross product. For example, a cross join between the employees and departments tables yields a result set with one row for each possible employees/departments combination.