Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 48/ 160
03. Joins & Relational Querying

CROSS JOIN (Cartesian Products & Use Cases)

Generate intentional Cartesian products for calendars, combos, and scaffolds.

IntermediateCROSS JOIN · Cartesian Product3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Match everything in one list with everything in another list. Three shirts and four trousers make twelve outfits.

Think of it like…

A restaurant menu builder: every main dish combined with every side dish gives the full list of possible meals, whether or not anyone has ever ordered them.

Where you’ve seen it

Daily sales per product with zeros for days without sales: SELECT d.day, p.id, COALESCE(SUM(s.qty), 0) FROM calendar d CROSS JOIN products p LEFT JOIN sales s ON s.product_id = p.id AND s.sold_on = d.day GROUP BY d.day, p.id;

Words you’ll hear

Cartesian product
Every combination of rows from two sets: |A| × |B| rows.
Scaffold
A complete grid of dimension combinations that facts are joined onto.
Accidental cross join
A missing or wrong join condition that multiplies rows.
Single-row cross join
Attaching one summary row (like a grand total) to every row.

Visual diagram

Loading interactive diagram

Theory & example queries

Intentional uses

Scaffolding: cross join the dimensions you want complete (dates × products, stores × hours), then LEFT JOIN the facts and COALESCE missing values to 0. Charts and pivot tables then show zeros instead of silently skipping combinations.

Generating combinations: sizes × colours for product variants, or every pair of A/B test variants and segments. Attaching a single value: CROSS JOIN (SELECT SUM(amount) AS total FROM orders) t puts the grand total on every row so you can compute shares, though SUM(amount) OVER () usually does the same more simply.

Product variantsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  s.size,3  c.colour4FROM5  sizes s6  CROSS JOIN colours c;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
sizecolour
SBlack
SBlue
MBlack
MBlue

Note: Shows 4 of the 20 combinations produced by sample sets of 4 sizes and 5 colours.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

4 sizes × 5 colours = 20 variants.

Key takeaway: Cross join the dimensions, then left join the facts.

Accidental Cartesian products

The old comma syntax, FROM orders, customers WHERE …, is a cross join filtered by WHERE. Forget the join condition and every order pairs with every customer: a million orders and 100,000 customers become 100 billion rows, and the query runs until something times out.

A wrong or incomplete join condition can do the same more quietly, for example joining only on a low-cardinality column like country. Use explicit JOIN … ON syntax, and sanity-check row counts against what the grain should be.

How a missing condition explodesQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  *3FROM4  orders o,5  customers c6WHERE7  o.created_at > now() - interval '1 day';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
order_idorder_customer_idpaired_customer_id
90014242
90014277
90027742
90027777

Note: Illustrates the accidental Cartesian product from 2 recent orders and 2 customers; SELECT * would include all remaining columns.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns every recent order paired with every customer, not each order with its customer.

Key takeaway: Use explicit JOIN … ON, and compare row counts with the expected grain.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Decide which grid must be complete

Pick the dimensions every report row should exist for, such as every day in the range for every active product.

Focus at this step

days × products

What to watch at this step
Rows
|days| × |products|
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

CROSS JOIN pairs every row of one table with every row of another, a Cartesian product, so 30 dates × 50 products gives 1,500 rows. It has no ON condition. Used on purpose, it builds scaffolds and combinations; by accident (a forgotten join condition), it explodes row counts.

Why it matters: Reports often need a row for every combination, including the ones with no data: every product on every day, with zero sales filled in. CROSS JOIN builds that grid. Interviewers ask about it both as a join type and to see whether you recognise an accidental Cartesian product.

When to reach for it

  • Filling date × dimension grids for charts
  • Generating variants and combinations
  • Building test or synthetic data

When to avoid or be careful

  • Comma joins without conditions
  • Cross joining large tables without estimating the row count
  • Using CROSS JOIN where a window function would attach the value more simply

CROSS JOIN vs window function vs inner join

CROSS JOIN scaffold
Best for: Complete grids with zero-filled gaps

Strengths: Every combination appears in the result.

Watch out: Rows multiply quickly; size the inputs first.

SUM() OVER ()
Best for: Attaching a grand total to every row

Strengths: No join needed.

Watch out: Only works within the same result set.

INNER JOIN on facts
Best for: Only combinations that actually have data

Strengths: Smallest result.

Watch out: Missing combinations simply don't appear.

Interview signals & numbers to know

When this topic comes up

  • “Show zero for days with no sales”
  • “Every combination of …”
  • A query that never finishes after a join change
  • Row counts far above expectations
  • Types of joins

Benchmarks & rules of thumb

|A| × |B| -
rows produced
30 × 50 -
= 1,500 rows
0 -
ON conditions in a CROSS JOIN

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting a join condition in comma syntax and generating billions of rows.
  • Using an INNER JOIN to sales instead of a LEFT JOIN after the scaffold, which removes the zero rows again.
  • Cross joining before filtering, so the grid is far larger than needed.

Likely interviewer follow-ups

  • How would you show daily sales for every product, including days with zero sales?
  • What happens if you forget the WHERE condition in FROM a, b?
  • When is a CROSS JOIN with a one-row subquery useful?
Interview tip: Give the scaffold example (dates × products, then LEFT JOIN facts). It's the use case interviewers want, and it shows you know CROSS JOIN is useful, not just dangerous.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply CROSS JOIN (Cartesian Products & Use Cases) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
FULL OUTER JOIN & Data Reconciliation Queries
Next topic
SELF JOIN for Hierarchical & Peer Comparisons