CROSS JOIN and self joins: combinations and hierarchies
Overview
A CROSS JOIN generates all pairs of rows from two inputs, with no matching predicate. A self join is a join between two aliases of the same table, useful for relationships such as employees and their managers. Self join describes the inputs, not a separate SQL join keyword.
First example
SELECT c.id, p.idFROM customers AS c CROSS JOIN products AS pORDER BY c.id, p.id;Observed SQLite result (rows in JSON):
[ [ 1, 1 ], [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 2, 1 ], [ 2, 2 ], [ 2, 3 ], [ 2, 4 ], [ 3, 1 ], [ 3, 2 ], [ 3, 3 ], [ 3, 4 ]]How it works
The first example lists combinations of three customers and four products: 12 rows, not seven. It describes possible combinations, not actual purchases. A missing ON predicate can produce an unintended product in engines with permissive syntax such as SQLite. The second example uses join_staff twice, as e for employee and m for manager. e.manager_id = m.id finds the immediate manager; the left join keeps Mina, who has no manager. This is one level of hierarchy, not recursive traversal. Use aliases and explicit qualification. CROSS JOIN can constrain planner join reordering in SQLite; this is engine-specific and not a general performance recommendation.
Practical example
SELECT e.id, e.name, m.name AS managerFROM join_staff AS e LEFT JOIN join_staff AS m ON e.manager_id = m.idORDER BY e.id;Observed SQLite result (rows in JSON):
[ [ 1, "Mina", null ], [ 2, "Reza", "Mina" ], [ 3, "Neda", "Mina" ], [ 4, "Omid", "Reza" ]]Practice and mistakes
Practice: list unordered pairs of different products by joining products to itself using a.id < b.id. Predict six pairs: each pair occurs once because the smaller id is always on the left. Do not use a.id <> b.id if you intend to exclude reversed duplicates. Test small cardinalities before joining large inputs.