Skip to main content
Beginnercomparison

Explain a self join and a cross join in SQL, with an example where each is useful.

ReportedSource: GeeksforGeeks interview experience: Amazon Data Engineer

Quick answer

Self join: a table joined to itself with aliases (employee to manager). Cross join: Cartesian product of two tables (store x date grid for gap-filling). Watch for accidental cross joins inflating results.

Self join. A table joined to itself using two aliases. Useful for hierarchies or comparing rows of the same table.

query.sql
-- each employee with their manager's name
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id;

Other uses: pairs of customers in the same city, finding consecutive events by joining a row to the next one (window functions such as LAG often replace this today).

Cross join. The Cartesian product: every row of A paired with every row of B, with no join condition. Result size = rows(A) x rows(B).

query.sql
-- a row for every store and every date, to report zero-sales days
SELECT s.store_id, d.date
FROM stores s CROSS JOIN calendar d;

Then LEFT JOIN the sales facts onto this grid and COALESCE(sales, 0).

Warning. An accidental cross join (a missing ON condition) multiplies rows and silently inflates sums; check row counts after joins.

See the concept: Join fan-out

Join fan-out
order_lines: one row per line
O101line 1₹300
payments: one row per attempt
O101P101FAILED
O101P102SUCCESS
lines JOIN payments ON order_id
line 1P101₹300
line 1P102₹300
SUM(line_revenue)₹600

Wrong: the single ₹300 line is counted once per payment attempt.

Fix: aggregate payments to one row per order first

line 1, paid, ₹300, so SUM = ₹300

One order line, two payment attempts: a direct join doubles the revenue. Aggregating payments to order grain first keeps one row per line.

Discussion