Module 15 · Lesson 6 of 14Detailed study · about 25 min

Join explosion: fix the result before the runtime

A join explosion occurs when matching keys produce many more intermediate rows than expected. It can make a query both expensive and incorrect.

Your learning goal

Predict join output, diagnose missing predicates and duplicate dimension keys, and preserve the intended business grain.

Understand the idea

A concrete example

Each of the six orders should match one customer. If customer 1 occurs twice in a dimension, both of that customer’s orders match twice. The intermediate result grows to eight rows, and paid revenue rises incorrectly from 650 to 900.

Key ideas in simple English
ConceptWhat it means
GrainWhat one row represents, such as one order.
CardinalityThe number of rows or distinct values at an operator.
Many-to-many joinMultiple rows on both sides match the same key.
Cartesian joinEvery left row combines with every right row.

Remember: Check grain, key multiplicity and join predicates first. Validate correct totals before investigating the remaining runtime.

Explain it step by step · full theory

Learning goals and prerequisites

Predict join output, diagnose missing predicates and duplicate dimension keys, and preserve the intended business grain.

Use the M15_LAB setup from lesson 1. Know SELECT, joins, aggregates and window functions from Modules 03–04. Follow the supplied examples with an authorized warehouse and an isolated learning role. Keep the same data and account context when comparing runs.

Count matches before tuning

Each of the six orders should match one customer. If customer 1 occurs twice in a dimension, both of that customer’s orders match twice. The intermediate result grows to eight rows, and paid revenue rises incorrectly from 650 to 900.

An intentionally many-to-many relationship is not inherently wrong. The issue is whether the output grain matches the business question.

Read the expanding operator

Inspect both join inputs and output rows in Query Profile. A cross join of six orders with three customers creates eighteen rows. A missing part of a composite key can produce a similar surprise while still looking like a normal JOIN.

Check uniqueness of the intended dimension key and identify duplicate keys. Standard table primary-key declarations do not generally enforce uniqueness, so ingestion validation matters.

Repair semantics explicitly

Remove an accidental duplicate only after deciding which source record is authoritative. A slowly changing dimension may require effective-date predicates rather than SELECT DISTINCT. DISTINCT on the final aggregate cannot undo revenue already multiplied.

If the business needs only existence, an EXISTS predicate can express that requirement without multiplying the left rows. When measures from both sides are needed, consider pre-aggregating each side to the required grain before joining.

Production investigation

First check the join predicate and row counts, then filter input and examine skew. Increasing memory might reduce spilling while leaving the incorrect multiplication intact. Validate totals and key counts before measuring the corrected query.

Common mistakes and next action

An aggregate can already contain duplicated measures. Repair the relationship before aggregation.

Check grain, key multiplicity and join predicates first. Validate correct totals before investigating the remaining runtime.

Words used in this lesson
Grain
What one row represents, such as one order.
Cardinality
The number of rows or distinct values at an operator.
Many-to-many join
Multiple rows on both sides match the same key.
Cartesian join
Every left row combines with every right row.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 3

Join explosion: fix the result before the runtime

5 paid orders
Unique dimension
5 matches

Expected grain

One paid order matches one customer: five rows enter the aggregate.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. Expected grain

    One paid order matches one customer: five rows enter the aggregate.

    5 paid orders → Unique dimension → 5 matches

  2. Duplicate key

    Two orders for customer 1 each gain an extra match.

    Customer 1 × 2 → 7 matches → Revenue 900 · wrong

  3. Repair

    Use the authoritative key or correct temporal predicate before benchmarking.

    Validate key → 5 matches → Revenue 650 · correct

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

Manual examples for L2_OBJECTS_LAB.M15_LAB. Select an authorized warehouse and a role with database/schema access and permission to create the lab objects. Setup runs once with fresh names. Optional paid services require their stated privileges and edition. SQL and performance timings have not been executed or measured for this lesson.

Reproduce a duplicate customer key

SQL · example
CREATE TEMPORARY TABLE CUSTOMERS_DUP AS SELECT * FROM CUSTOMERS;
INSERT INTO CUSTOMERS_DUP VALUES(1,'west');
SELECT CUSTOMER_ID,COUNT(*) AS N FROM CUSTOMERS_DUP
GROUP BY CUSTOMER_ID HAVING COUNT(*)>1;
SELECT COUNT(*) AS JOINED_ROWS,SUM(o.AMOUNT) AS PAID_REVENUE
FROM ORDERS o JOIN CUSTOMERS_DUP c ON o.CUSTOMER_ID=c.CUSTOMER_ID
WHERE o.STATUS='paid';

What to expect and why

The second result is seven paid joined rows and 900 revenue, logically derived from the fixture. Two paid orders for customer 1 are counted twice.

Expected result for the supplied input (not live output)
JOINED_ROWSPAID_REVENUE
7900.00

Use the validated dimension

SQL · example
SELECT COUNT(*) AS JOINED_ROWS,SUM(o.AMOUNT) AS PAID_REVENUE
FROM ORDERS o JOIN CUSTOMERS c ON o.CUSTOMER_ID=c.CUSTOMER_ID
WHERE o.STATUS='paid';
SELECT o.ORDER_ID FROM ORDERS o
WHERE EXISTS(SELECT 1 FROM CUSTOMERS_DUP c WHERE c.CUSTOMER_ID=o.CUSTOMER_ID)
ORDER BY o.ORDER_ID;

What to expect and why

The paid join returns five rows and 650. EXISTS returns all six order IDs once each; it answers customer existence, not regional aggregation.

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

Will DISTINCT after SUM reliably repair an exploding join?

Try it yourself

Predict row counts for the full cross join and for the duplicate-key inner join before running either.

Compare your reasoning

Check grain, key multiplicity and join predicates first. Validate correct totals before investigating the remaining runtime.

Key takeaway

Check grain, key multiplicity and join predicates first. Validate correct totals before investigating the remaining runtime.

Connect this lesson to the learning path

Official sources and curriculum

Module 15 · See module scope

By Rohit Ray · Independent educational lesson · Explore this visual lab