Explain a self join and a cross join in SQL, with an example where each is useful.
ReportedSource: GeeksforGeeks interview experience: Amazon Data Engineer
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.
-- 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).
-- 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
| O101 | line 1 | ₹300 |
| O101 | P101 | FAILED |
| O101 | P102 | SUCCESS |
| line 1 | P101 | ₹300 |
| line 1 | P102 | ₹300 |
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