Sub topic 1
What a join does
Prerequisites
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, how primary and foreign keys link tables, how table aliases work, and how NULL behaves in comparisons. The examples use the sample HR tables employees and departments.
What a join does
A join combines rows from two tables when their columns match a condition. Each employee row points to a department through department_id, and the join uses that link.
Inner joins: ANSI syntax and the comma syntax side by side
An inner join returns only rows that match. Both queries below return the same result. The first uses the ANSI INNER JOIN ... ON form, and the second uses the older comma form.
SELECT e.employee_id, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;SELECT e.employee_id, e.last_name, d.department_name
FROM employees e, departments d
WHERE e.department_id = d.department_id;Prefer the ANSI form. Its join condition sits next to the tables it connects, so a missing condition is easier to spot.
Keeping unmatched rows with LEFT and RIGHT OUTER JOIN
An inner join drops rows that have no match. A LEFT OUTER JOIN keeps every row from the left table and fills the right-side columns with NULL when no match exists. A RIGHT OUTER JOIN does the same for the right table.
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id;A department with no employees still appears, with NULL in last_name.
Where the filter goes: ON versus WHERE
In an outer join, a condition in ON decides which right-side rows match. A condition in WHERE runs after the join and can remove the NULL-filled rows.
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id
AND e.salary > 10000;This query keeps every department. Departments without a high earner show NULL.
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id
WHERE e.salary > 10000;This query drops every department without a matching high earner, so it behaves like an inner join.
Exercise
Which query returns more rows, the ON version or the WHERE version?
Show answer
The ON version. It keeps every department, including departments with no employee earning over 10000. The WHERE version removes those departments, so it returns a subset of the ON version's rows.