In this post we are going to cover the CROSS JOIN in Snowflake.
A CROSS JOIN pairs every row of one table with every row of the other. It has no ON clause, because there is nothing to match. It compares nothing and it drops nothing.
We will start with the join itself, then work out where its row count comes from, then write the same thing with a comma instead of a keyword, which is how most people end up with one by accident. After that we will look at the two jobs a cross join is genuinely the right tool for.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 27 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with a join that has no ON clause
- Now let's see where that row count comes from
- Now let's write the same thing with a comma
- Let's add one line and see what changes
- Can a cross join be the right answer? Let's build a grid
- Now let's attach one value to every row
- So how do we tell deliberate from accidental?
Let's create some sample data
We need two tables to pair up. If you have been following this level you already have them: EMPLOYEES from Episode 1 and DEPARTMENTS from Episode 24. The script below is the whole of both, so you can start from here.
-- Both tables already exist if you have followed Level 3 from the start:
-- EMPLOYEES was created in Episode 1, DEPARTMENTS in Episode 24. This is the
-- whole of both of them, so you can paste it into a worksheet and follow along.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE EMPLOYEES (
EMP_ID INT,
FIRST_NAME VARCHAR,
LAST_NAME VARCHAR,
EMAIL VARCHAR,
DEPT_ID INT,
MANAGER_ID INT,
SALARY NUMBER(10,2),
COMMISSION_PCT NUMBER(4,2),
HIRE_DATE DATE
);
INSERT INTO EMPLOYEES VALUES
(1, 'Aisha', 'Khan', 'aisha.khan@example.com', 10, 6, 118000.00, NULL, '2019-03-11'),
(2, 'Marcus', 'Reid', 'marcus.reid@example.com', 10, 6, 96500.00, NULL, '2021-07-01'),
(3, 'Lena', 'Fischer', 'lena.fischer@example.com', 20, 6, 104000.00, 0.05, '2018-01-22'),
(4, 'Tomas', 'Novak', 'tomas.novak@example.com', 20, 3, 87250.00, NULL, '2022-09-05'),
(5, 'Priya', 'Raman', 'priya.raman@example.com', 30, 6, 96500.00, 0.10, '2020-11-17'),
(6, 'Daniel', 'O''Connor', 'daniel.oconnor@example.com', 10, NULL, 131000.00, NULL, '2016-05-30'),
(7, 'Sofia', 'Marino', 'sofia.marino@example.com', 30, 5, 71400.00, 0.08, '2023-02-13'),
(8, 'Grace', 'Lin', 'grace.lin@example.com', NULL, 6, 92000.00, NULL, '2021-04-19');
CREATE OR REPLACE TABLE DEPARTMENTS (
DEPT_ID INT,
DEPT_NAME VARCHAR,
LOCATION VARCHAR,
BUDGET NUMBER(12,2)
);
INSERT INTO DEPARTMENTS VALUES
(10, 'Engineering', 'Charlotte', 2400000.00),
(20, 'Finance', 'Charlotte', 1100000.00),
(30, 'Marketing', 'Raleigh', 750000.00),
(40, 'Operations', 'Raleigh', 640000.00);Count the two INSERT lists and you have the two numbers this whole page turns on. The employee list is eight rows long. The department list is four. Hold on to those.
For this post the contents of the two tables barely matter. A cross join does not compare anything and does not drop anything, so all it cares about is how many rows each table holds.
This episode did not re-capture a SELECT * of either table, so you will not find one on this page. We are not taking the two sizes on trust either. Two sections down, Snowflake counts both tables itself and the grid is right there.
One more table turns up near the end, ORDERS, created by the shared sample-data script for this course. The only thing we ask of it is the set of distinct values in its STATUS column, and those values are visible in the grid that uses them.
Let's start with a join that has no ON clause
An inner join draws a line between two rows only when something matches. An outer join draws that same line and then decides what to do with the rows that have no line at all. A cross join draws every line.
So we write CROSS JOIN and we stop. There is no ON clause, because there is nothing to put in one.
SELECT E.FIRST_NAME, D.DEPT_NAME
FROM EMPLOYEES E
CROSS JOIN DEPARTMENTS D
ORDER BY E.EMP_ID, D.DEPT_ID;| FIRST_NAME | DEPT_NAME |
|---|---|
| Aisha | Engineering |
| Aisha | Finance |
| Aisha | Marketing |
| Aisha | Operations |
| Marcus | Engineering |
| Marcus | Finance |
| Marcus | Marketing |
| Marcus | Operations |
| Lena | Engineering |
| Lena | Finance |
| Lena | Marketing |
| Lena | Operations |
| Tomas | Engineering |
| Tomas | Finance |
| Tomas | Marketing |
| Tomas | Operations |
| Priya | Engineering |
| Priya | Finance |
| Priya | Marketing |
| Priya | Operations |
| Daniel | Engineering |
| Daniel | Finance |
| Daniel | Marketing |
| Daniel | Operations |
| Sofia | Engineering |
| Sofia | Finance |
| Sofia | Marketing |
| Sofia | Operations |
| Grace | Engineering |
| Grace | Finance |
| Grace | Marketing |
| Grace | Operations |
Read the FIRST_NAME column down the page. Aisha four times, then Marcus four times, then Lena, and on through the whole employee list. Each employee is paired with each of the four departments exactly once.
Two things in that grid are worth stopping on. Grace is in it. Her DEPT_ID is NULL, which was enough to lose her from the inner join in Episode 24, and here it is never looked at. And Operations is in it, paired with everybody, even though no employee works there.
Nothing was compared, so nothing could fail to match, so nothing was dropped. The usual question about a join, which rows went missing, has no answer here. The question does not apply.
Now let's see where that row count comes from
The size of that result is a multiplication. The number of rows on the left, times the number of rows on the right. Let's have Snowflake do that arithmetic itself, so none of the three numbers comes from us.
SELECT
(SELECT COUNT(*) FROM EMPLOYEES) AS EMPLOYEES,
(SELECT COUNT(*) FROM DEPARTMENTS) AS DEPARTMENTS,
(SELECT COUNT(*) FROM EMPLOYEES CROSS JOIN DEPARTMENTS) AS CROSS_ROWS;| EMPLOYEES | DEPARTMENTS | CROSS_ROWS |
|---|---|---|
| 8 | 4 | 32 |
Eight. Four. Thirty-two. Every other join in this level gives us a count we have to reason about. A cross join gives us one we can work out in our head before we run it.
The same relationship read backwards is a useful diagnostic. If a join you believed was matching rows comes back with exactly the product of the two table sizes, your join condition is not being applied, whatever the query looks like.
Now let's write the same thing with a comma
Here is the part that makes this post matter. SQL has an older way of listing two tables. We put both of them in the FROM clause, separated by a comma, with no join keyword anywhere.
SELECT E.FIRST_NAME, D.DEPT_NAME
FROM EMPLOYEES E, DEPARTMENTS D
ORDER BY E.EMP_ID, D.DEPT_ID;| FIRST_NAME | DEPT_NAME |
|---|---|
| Aisha | Engineering |
| Aisha | Finance |
| Aisha | Marketing |
| Aisha | Operations |
| Marcus | Engineering |
| Marcus | Finance |
| Marcus | Marketing |
| Marcus | Operations |
| Lena | Engineering |
| Lena | Finance |
| Lena | Marketing |
| Lena | Operations |
That is the same result as the CROSS JOIN we ran earlier, down to the row order. And the word CROSS does not appear anywhere in the query.
This is why an accidental cross join is so hard to spot in review. It does not look like a mistake. It looks like a shorter query. There is no error, no warning, and no NULL standing in for something missing. Just more rows than anybody wanted.
Let's add one line and see what changes
Now let's add a WHERE clause to that query, comparing the two department IDs. Nothing else changes.
SELECT E.FIRST_NAME, D.DEPT_NAME
FROM EMPLOYEES E, DEPARTMENTS D
WHERE E.DEPT_ID = D.DEPT_ID
ORDER BY E.EMP_ID;| FIRST_NAME | DEPT_NAME |
|---|---|
| Aisha | Engineering |
| Marcus | Engineering |
| Lena | Finance |
| Tomas | Finance |
| Priya | Marketing |
| Daniel | Engineering |
| Sofia | Marketing |
Seven rows. They are the same seven the inner join returned in Episode 24, in the same order, with Grace and Operations gone again. The comma form with a WHERE clause is an inner join written the old way.
The FROM clause | Plus | Rows back | What it really is |
|---|---|---|---|
FROM EMPLOYEES E, DEPARTMENTS D | nothing | 32 | A cross join |
FROM EMPLOYEES E, DEPARTMENTS D | WHERE E.DEPT_ID = D.DEPT_ID | 7 | An inner join |
Same syntax, same two tables, one line between them. That is the whole difference between a result we meant and a result we did not.
Why that is harmless here and dangerous elsewhere
On this data the mistake is obvious. The grid is visibly far too long and we notice. That is only true because the tables are tiny.
Put the same omission in front of 8,000,000 employees and 4,000 departments and it asks for 32,000,000,000 rows. The query is still valid. It does not fail, and nothing in the SQL text hints at why it never comes back. The only clue is a FROM clause with a comma in it and no matching condition.
Those two table sizes are invented for the sake of the arithmetic. Nothing on this page was timed or benchmarked, and no duration is being claimed.
So this is the strongest argument for writing joins the modern way. INNER JOIN ... ON ... puts the join condition next to the tables it joins, where a missing one is a visible hole. And when we genuinely want every pairing, writing CROSS JOIN says so in a word that survives code review.
Can a cross join be the right answer? Let's build a grid
A post that only says “danger” teaches people to avoid a tool they are going to need. So here is the first case where a cross join is exactly what we want.
Say a report has a row for every department and a column for every order status. If we only aggregate the orders we get the combinations that actually happened. A department with no cancelled orders has no row at all, and the report skips it instead of showing a zero.
So let's build the full set of combinations first, out of the two lists themselves, with no order data involved.
SELECT D.DEPT_NAME, S.STATUS
FROM DEPARTMENTS D
CROSS JOIN (SELECT DISTINCT STATUS FROM ORDERS) S
ORDER BY D.DEPT_NAME, S.STATUS;| DEPT_NAME | STATUS |
|---|---|
| Engineering | CANCELLED |
| Engineering | PENDING |
| Engineering | RETURNED |
| Engineering | SHIPPED |
| Finance | CANCELLED |
| Finance | PENDING |
| Finance | RETURNED |
| Finance | SHIPPED |
| Marketing | CANCELLED |
| Marketing | PENDING |
| Marketing | RETURNED |
| Marketing | SHIPPED |
| Operations | CANCELLED |
| Operations | PENDING |
| Operations | RETURNED |
| Operations | SHIPPED |
Four department names crossed with four distinct status values, and sixteen rows back. Every pairing is there, including the ones no order has ever landed in. Left join our aggregated totals onto that grid and the empty combinations come back as NULL, which COALESCE turns into the zero the report should have shown all along.
Note where the second list came from: SELECT DISTINCT STATUS FROM ORDERS, a subquery in the FROM clause. A cross join does not care that one side is a table and the other a derived result. It pairs rows with rows.
Now let's attach one value to every row
The second case is the safe one, and it is safe for a reason that falls straight out of the arithmetic. If one side has exactly one row, the product is the other side unchanged.
Say we want every employee's salary next to the company-wide average, and the gap between the two. The average is a single value, one row and one column, so let's cross join it onto the table.
SELECT E.FIRST_NAME, E.SALARY, T.AVG_SALARY,
E.SALARY - T.AVG_SALARY AS DIFF_FROM_AVG
FROM EMPLOYEES E
CROSS JOIN (SELECT AVG(SALARY) AS AVG_SALARY FROM EMPLOYEES) T
ORDER BY E.EMP_ID;| FIRST_NAME | SALARY | AVG_SALARY | DIFF_FROM_AVG |
|---|---|---|---|
| Aisha | 118000.00 | 99581.25000000 | 18418.75000000 |
| Marcus | 96500.00 | 99581.25000000 | -3081.25000000 |
| Lena | 104000.00 | 99581.25000000 | 4418.75000000 |
| Tomas | 87250.00 | 99581.25000000 | -12331.25000000 |
| Priya | 96500.00 | 99581.25000000 | -3081.25000000 |
| Daniel | 131000.00 | 99581.25000000 | 31418.75000000 |
| Sofia | 71400.00 | 99581.25000000 | -28181.25000000 |
| Grace | 92000.00 | 99581.25000000 | -7581.25000000 |
The same eight employees went in and came back, each one carrying the average and its own difference from it. AVG_SALARY repeats identically down the grid, because there was only ever one value to attach. DIFF_FROM_AVG is positive for the people above the average and negative for the people below it.
The row count did not move. That is what makes this pattern worth reaching for. The thing that makes cross joins frightening is the multiplication, and multiplying by one changes nothing.
You could get the same columns by repeating a scalar subquery in the SELECT list, but then the aggregate is written once per column that needs it. Crossing against it names the value once and uses it everywhere, which is easier to read and harder to get subtly wrong.
This pattern is only safe while that subquery really does return a single row. Drop a GROUP BY into it and it starts returning one row per group. Your row count starts multiplying again, silently, in a query that used to be fine.
So how do we tell deliberate from accidental?
Every cross join falls into one of two groups, and the difference is never in the syntax. It is in whether the person who wrote it could tell you the expected row count before running it.
| Signal | Deliberate | Accidental |
|---|---|---|
| How it is written | The words CROSS JOIN, on purpose | A comma in the FROM clause |
| The other side | A short list, or a single-row aggregate | Another full-sized table |
| Expected row count | Known in advance, and usually unchanged or small | Nobody worked it out |
| What the result is for | A complete grid, or one value on every row | It was supposed to be a match |
Outside those two deliberate uses, a cross join in finished work is nearly always a join condition somebody forgot to write.
Key points
- A
CROSS JOINhas noONclause. It pairs every row of one table with every row of the other, and compares nothing. - Its row count is a multiplication, not a match: 8 employees and 4 departments give 32 rows, captured from the database on this page.
- Nothing is dropped, so rows that other joins lose — Grace with a
NULLkey, Operations with no employees — are all present. - A comma between two tables in the
FROMclause is a cross join. The wordCROSSdoes not have to appear anywhere. - Adding
WHERE E.DEPT_ID = D.DEPT_IDto that comma form turns 32 rows into 7. It is an inner join written the old way. - A missing join condition does not look like a bug, it looks like a shorter query, and on large tables the result is a query that never finishes rather than one that fails.
- Crossing two lists is the right way to build a complete grid, so a report can show a zero instead of silently skipping a combination.
- Crossing against a single-row subquery attaches one value to every row and leaves the row count exactly where it was.
- Prefer
JOIN ... ONfor matching and an explicitCROSS JOINwhen you mean it. Both make the intent survive code review.
In the next post we will look at USING versus ON, and NATURAL JOIN. Two shortcuts that write the join condition for us. One is a tidy convenience. The other picked its own columns and returned nothing at all.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the shared sample-data script for this course. The EMPLOYEES, DEPARTMENTS and ORDERS data is invented demo data created by that script. The large table sizes in the warning above are arithmetic on hypothetical tables, clearly marked as such: no performance or benchmark claims are made anywhere in this series, and nothing on this page was timed. Join behaviour is described from the Snowflake JOIN documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.