Skip to the solution
EasyDSA12 min read

What is a CROSS JOIN and when is it useful?

484 views

The problem

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 JOIN real 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, b and JOIN ... 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 TRUE to keep the left rows
  • Engine details: PostgreSQL rejects CROSS JOIN ... ON and a bare JOIN without ON, SQLite accepts both, and SQLite never reorders the two sides of a CROSS JOIN

Code / implementation expected: Yes β€” a combinations query and, ideally, a calendar or grid query that fills gaps.

Schema used by the examples:

  • joins

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 10 sections

Run the code

Edit the query and run it against the tables for this question.

SQLEvery product variant: 3 sizes Γ— 3 colors = 9 rows
SQLGap filling: a complete store Γ— month grid, with 0 where there were no sales
SQLAttach a one-row grand total to every row to compute a share
PostgreSQL: cross join with generate_series instead of a months table
SELECT st.name AS store, to_char(m, 'YYYY-MM') AS month,
       COALESCE(SUM(sa.amount), 0) AS revenue
FROM stores AS st
CROSS JOIN generate_series(DATE '2024-01-01', DATE '2024-04-01', INTERVAL '1 month') AS m
LEFT JOIN sales AS sa
  ON sa.store_id = st.id
 AND sa.month = to_char(m, 'YYYY-MM')
GROUP BY st.id, st.name, m
ORDER BY st.id, m;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 11 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextEasy

What is SQL injection and how do parameterized queries prevent it?

Continue