Question presented to candidate: "What does a CROSS JOIN return? Most people say you should never use one β can you give me a case where it is actually the right tool, and tell me what can go wrong with it?"
What a strong answer should cover:
- A CROSS JOIN returns the Cartesian product: every row of the left input paired with every row of the right, so the row count is n Γ m, with no join condition
- Legitimate uses: generating combinations (sizes Γ colors), building a complete grid (stores Γ months) to
LEFT JOINreal data onto so missing cells show as 0, and attaching a one-row result (a grand total, a config row) to every row - Equivalent spellings:
FROM a, bandJOIN ... ON TRUE; the danger is an accidental product from a forgotten join condition - If either side is empty the result is empty; use
LEFT JOIN ... ON TRUEto keep the left rows - Engine details: PostgreSQL rejects
CROSS JOIN ... ONand a bareJOINwithoutON, SQLite accepts both, and SQLite never reorders the two sides of aCROSS JOIN
Code / implementation expected: Yes β a combinations query and, ideally, a calendar or grid query that fills gaps.
Schema used by the examples: