Foundations › SQL › Combining Tables
🔗 Combining TablesMore Joins, Multi-Table Joins and the Row-Fan-Out Trap
Beyond INNER and LEFT there are other types you sometimes need. The most dangerous join problem is row fan-out, shown with an example.
| Type | Result |
|---|---|
| RIGHT JOIN | Every right row with its left match (rarely needed: swap tables and use LEFT) |
| FULL JOIN | All rows from both sides even without a match |
| CROSS JOIN | Every possible pairing between the tables (Cartesian product) |
| SELF JOIN | Joining a table to itself, like an employee and a manager |
Self join
The same table twice under different aliases: e for the employee, m for the manager. Open in SQL Lab
Joining several tables
Revenue per city: passing through three tables. Open in SQL Lab
The fan-out trap
One order has many items, so joining orders to order_items repeats the order row per item. Summing an order-level column (like shipping_fee) then multiplies it.
The second number is far bigger because of the repetition. Open in SQL Lab
For advanced readers CROSS JOIN and the calendar table
CROSS JOIN is handy to generate a full grid (every city × every month) then join data to it so zeros show instead of missing rows. FULL JOIN is not supported in MySQL; emulate it with LEFT JOIN UNION RIGHT JOIN.
Exercise 1 — Show each employee and their manager's name (NULL when none), sorted by employee name: employee and manager.
Join employees to itself on manager_id.
Exercise 2 — Show the top 5 customers by spend on completed orders: name and spent (quantity × unit_price).
Three tables: customers, orders, order_items.
Exercise 3 — Show every department with its employee count (shown even with none): department and employees.
LEFT JOIN from departments with COUNT(e.id).
- SELF JOIN links a table to itself.
- Multi-table joins walk through many tables in order.
- Beware fan-out: aggregate each table at its own level.
Want an expert to do it for you?
Gomaa Intelligence turns your data into clear reports and decisions. Tell us your problem and we will reply.