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 thedepartment_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, theemployee table stores only the department_id, not the department name.
If we execute the following query:
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
JOINspecifies the table to combine.ONspecifies 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?Solution
Solution
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.Solution
Solution
Practice
Display employees working in the HR departments.Solution
Solution
Practice
Display employee names, salaries, and department names for employees earning more than ₹70,000.Solution
Solution
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.Solution
Solution
Practice
Find employees who are not assigned to any departments.Solution
Solution
Practice
How does a LEFT JOIN differ from an INNER JOIN?Solution
Solution
- 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.