A join combines rows from two tables by matching columns. Most real queries need joins because related data is spread over several tables.
Sample data
supplier(sid, sname) has rows (1, Ravi), (2, Geeta), (3, Mike). supplies(sid, pid) has rows (1, 10), (1, 11), (2, 10), (4, 12). Supplier 3 supplies nothing and supplier 4 does not exist in supplier.
Inner join
Returns only rows that match in both tables.
SELECT s.sname, p.pid
FROM supplier s INNER JOIN supplies p ON s.sid = p.sid;
Result: Ravi-10, Ravi-11, Geeta-10.
Left outer join
Keeps all rows of the left table; unmatched right values are NULL.
SELECT s.sname, p.pid
FROM supplier s LEFT OUTER JOIN supplies p ON s.sid = p.sid;
Result adds Mike with NULL.
Right outer join
Keeps all rows of the right table. Result adds NULL with pid 12.
Full outer join
Keeps all rows of both tables. Result has Mike-NULL and NULL-12 as well. MySQL has no FULL OUTER JOIN; combine a left and a right join with UNION.
Equi join and natural join
An equi join uses = between columns. A natural join joins on all columns with the same name and shows each such column once.
SELECT * FROM supplier NATURAL JOIN supplies;
Tip: Prefer
JOIN ... ONover natural join in real projects. A natural join can silently change when someone adds a column with a matching name.
Summary
| Join | Keeps unmatched rows from |
|---|---|
| INNER | Neither table |
| LEFT OUTER | Left table |
| RIGHT OUTER | Right table |
| FULL OUTER | Both tables |
Common mistakes
- Leaving out the
ONcondition, which gives a Cartesian product with far too many rows. - Putting a filter for the right table in
WHEREafter a left join, which turns it back into an inner join.
Practice questions
- What is a join? Name its types.
- Differentiate inner join and left outer join.
- Write a query listing every supplier even if it supplied no part.
- What is a natural join?
- What happens if the join condition is missing?
Answers to the practice questions
- A join combines rows of tables on matching columns; types: inner, left, right, full outer, equi and natural.
- Inner returns only matches; left outer also keeps unmatched left rows with NULLs.
- A left outer join from supplier to supplies.
- A join on all columns that share a name, showing each once.
- The result is a Cartesian product: every row paired with every row.
Sources
- Official BCA syllabus Database Management Systems, course code CC202, Unit II
- Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, 3rd edition, McGraw-Hill
