SQL Joining Tables

In this tutorial you will learn how to join two tables to get combined data.

SQL Join Fundamentals

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.

| emp_id | emp_name     | hire_date  | dept_id |
|      1 | Ethan Hunt   | 2001-05-01 |       4 |
|      2 | Tony Montana | 2002-07-15 |       1 |
|      3 | Sarah Connor | 2005-10-18 |       5 |
|      4 | Rick Deckard | 2007-01-03 |       3 |
|      5 | Martin Blank | 2008-06-24 |    NULL |
| dept_id | dept_name        |
|       1 | Administration   |
|       2 | Customer Service |
|       3 | Finance          |
|       4 | Human Resources  |
|       5 | Sales            |
Table: employees Table: departments

Note: In order to join tables, data of the columns which are used for joining tables should match, not necessarily the column names.

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.

We will learn more about inner join in next chapter.

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).

We will learn more about these variations of the outer join in later chapters.

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.

We will learn more about cross join in upcoming chapters.

Your Feedback:

We would love to hear from you, please drop us a line.