Gomaa Intelligence.Data Hub
عربي

Foundations › SQL › Combining Tables

🔗 Combining Tables

More Joins, Multi-Table Joins and the Row-Fan-Out Trap

Lesson 13 / 14· 11 min

Beyond INNER and LEFT there are other types you sometimes need. The most dangerous join problem is row fan-out, shown with an example.

TypeResult
RIGHT JOINEvery right row with its left match (rarely needed: swap tables and use LEFT)
FULL JOINAll rows from both sides even without a match
CROSS JOINEvery possible pairing between the tables (Cartesian product)
SELF JOINJoining a table to itself, like an employee and a manager
AB

Self join

▶ Try it yourself

The same table twice under different aliases: e for the employee, m for the manager. Open in SQL Lab

Joining several tables

▶ Try it yourself

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.

▶ Try it yourself

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.

Exercise 2 — Show the top 5 customers by spend on completed orders: name and spent (quantity × unit_price).

Exercise 3 — Show every department with its employee count (shown even with none): department and employees.

Summary
  • 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.

Get your data analyzed by an expert ↗