Skip to main content

SQL JOINs

In a relational database, related data is usually stored in separate tables to avoid duplication. For example, instead of storing the department name for every employee, we store only the department_id in the employee table. Whenever we need the department name, we combine both tables using a JOIN. Throughout this chapter, we’ll use the following tables.

Departments

Employees

Notice that Ajay is not assigned to any departments.

Why Do We Need JOINs?

In a normalized database, related information is stored in different tables. For example, the employee table stores only the department_id, not the department name. If we execute the following query:
We get: Although we know the department IDs, we don’t know the department names. To retrieve the department name, we combine the employee and department tables using a JOIN.

JOIN Syntax

Explanation

  • JOIN specifies the table to combine.
  • ON specifies the matching condition.
  • The matching column is usually a Primary Key in one table and a Foreign Key in another.

Practice

Which clause specifies the matching condition between two tables?
The ON clause specifies how two tables should be matched.Example:

INNER JOIN

An INNER JOIN returns only the rows that have matching values in both tables. If a record exists in one table but has no matching record in the other table, it is not included in the result.

Example 1

Display employee names along with their department names.

Result

Notice that Ajay is not included because there is no matching departments.

Example 2

Display employees earning more than ₹60,000 along with their department names.

Result

Practice

Display employee names with their department names.

Practice

Display employees working in the HR departments.

Practice

Display employee names, salaries, and department names for employees earning more than ₹70,000.

LEFT JOIN

A LEFT JOIN returns all rows from the left table and only the matching rows from the right table. If no matching row exists in the right table, SQL fills those columns with NULL.

Example 1

Display all employees along with their department names.

Result

Notice that Ajay is included because LEFT JOIN returns every row from the employees table.

Example 2

Display employees along with department names and salaries.

Practice

Display all employees with their department names.

Practice

Find employees who are not assigned to any departments.

Practice

How does a LEFT JOIN differ from an INNER JOIN?
  • INNER JOIN returns only matching rows.
  • LEFT JOIN returns all rows from the left table and matching rows from the right table.
  • If there is no match, the right table columns contain NULL.