Joins

keypoints:

  • "Joins are used to combine data from two or more tables."
  • "Tables to be joined must have a column in each which represent the same thing"
  • "There are several different types of joins"
  • "The Inner join is the most commonly use"

About table joins

In any relational database system, the ability to join tables together is a key querying requirement. Joins are used to combine the rows from two (or more) tables together to form a single table. A join between tables will only be possible if they have at least one column in common. The column doesn’t have to have the same name in each table, and quite often they won’t, but they do have to have a common usage.

If you look at the Schema for the staff database in DB Browser you will see that the department table and the employees table both contain a common column 'dept_id'. This means that there is a relationship between the two tables; inserting a dept_id no in the employee record makes details in the department table potentially available. We can use an SQL joining statement to list employees along with their relevant department.

select first_name, last_name, dept_name from employees 
join departments on employees.dept_id = departments.dept_id;

And we can order them by department

select first_name, last_name, dept_name from employees 
join departments on employees.dept_id = departments.dept_id
order by dept_name;