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 ... ON over 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 ON condition, which gives a Cartesian product with far too many rows.
  • Putting a filter for the right table in WHERE after a left join, which turns it back into an inner join.

Practice questions

  1. What is a join? Name its types.
  2. Differentiate inner join and left outer join.
  3. Write a query listing every supplier even if it supplied no part.
  4. What is a natural join?
  5. What happens if the join condition is missing?

Answers to the practice questions

  1. A join combines rows of tables on matching columns; types: inner, left, right, full outer, equi and natural.
  2. Inner returns only matches; left outer also keeps unmatched left rows with NULLs.
  3. A left outer join from supplier to supplies.
  4. A join on all columns that share a name, showing each once.
  5. 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