What you will be able to do
- Choose the grain an analysis needs and spot when a join or aggregation changes it
- Predict which rows survive INNER, OUTER, CROSS, NATURAL and LATERAL joins
- Stack and compare result sets with UNION, UNION ALL, INTERSECT and MINUS
- Write an ASOF JOIN with a correct MATCH_CONDITION and ON clause
- Place a filter in WHERE, HAVING or QUALIFY according to when it must run
1.Grain: what one row stands for
Grain is what a single row represents: one project, one employee, one order line, one trade. Once discovery has shown which tables hold the columns a question needs, the next decision is the grain the answer should come out at. Joins and aggregations both change grain, and a total summed at the wrong grain doesn't throw an error. It just comes out wrong.
Take a projects table with one row per project, where each project_id is unique, and an employees table with one row per employee, each carrying the project_id they work on. A join produces, for each project row, one row for each matching employee. COVID-19 Vaccine has two employees, so it appears twice in the result, and the grain is now one row per project-employee pair. This is fan-out: whenever the join key is not unique on the other side, a row is repeated once per match. Any number stored at project level is counted twice for that project if you add it up after the join.
Before you join, check that the key is unique on the side you expect to be unique (COUNT(DISTINCT key) equals COUNT(*)). If it isn't, aggregate that side to the grain you want first. Leaving out the join condition altogether is the extreme case: every row on one side is paired with every row on the other. That Cartesian product is huge, almost entirely made of unrelated pairs, and usually a mistake. Aggregation works in the other direction: GROUP BY collapses rows to one per group, so the grain gets coarser.
Checkpoint 1 of 9· Check yourself
projects has one row per project and a budget column. employees has one row per employee, and each row carries a project_id. Two employees work on COVID-19 Vaccine. An analyst runs SELECT p.project_name, SUM(p.budget) FROM projects p JOIN employees e ON e.project_id = p.project_id GROUP BY p.project_name. What happens to COVID-19 Vaccine's total?
A join produces one output row for each matching row on the other side. Because project_id repeats in employees, the COVID-19 Vaccine row appears twice and SUM counts its budget twice. GROUP BY runs after the join, so it groups the repeated rows but does not remove them. Snowflake raises no error. To avoid this, check uniqueness or aggregate employees to project grain before joining.
“For each row of o1, a row is produced for each row of o2 that matches according to the ON condition subclause.”Source: docs.snowflake.com
2.Which rows each join type keeps
Join types differ in what they do with rows that have no match. A plain JOIN with no INNER or OUTER keyword is an inner join, so unmatched rows disappear unless you ask for an outer join:
| Join | Rows returned | Unmatched rows |
|---|---|---|
| o1 INNER JOIN o2 | For each o1 row, one row per matching o2 row | Dropped from both sides |
| o1 LEFT OUTER JOIN o2 | Inner-join rows plus each unmatched o1 row | o2 columns are NULL |
| o1 RIGHT OUTER JOIN o2 | Inner-join rows plus each unmatched o2 row | o1 columns are NULL |
| o1 FULL OUTER JOIN o2 | Joined rows plus unmatched rows from both sides | Missing side is NULL |
| o1 CROSS JOIN o2 | Every combination (Cartesian product); ON not allowed | Not applicable |
| o1 NATURAL JOIN o2 | Join on all same-named columns, which appear once in the output; ON not allowed | Depends on the INNER or OUTER variant |
SELECT p.project_name, e.employee_name
FROM projects AS p LEFT OUTER JOIN employees AS e
ON e.project_ID = p.project_ID
ORDER BY p.project_name, e.employee_name;
+------------------+-----------------+
| PROJECT_NAME | EMPLOYEE_NAME |
|------------------+-----------------|
| COVID-19 Vaccine | Maria Inverness |
| COVID-19 Vaccine | Terry Smith |
| Malaria Vaccine | Pat Wang |
| NewProject | NULL |
+------------------+-----------------+In the result, NewProject survives with a NULL employee because the left table is preserved. The employee called NewEmployee is missing, because their project_id is NULL and matches no project. Swapping in RIGHT OUTER JOIN would keep NewEmployee and drop NewProject. An inner join would drop both. When discovery is about finding orphans, the outer join that preserves the side you are auditing is the right tool.
LATERAL works differently. In a FROM clause, it lets an inline view refer to columns from the table expressions before it, so the subquery runs against each left-hand row, much like a correlated subquery. Unlike a correlated subquery, it can return several rows with several columns each. The output contains only the rows the inline view generates; they are not cross-joined back to every row on the left. The common pattern is LATERAL FLATTEN, which unpacks an ARRAY or VARIANT value into rows. The function itself is covered with the other Snowflake functions.
Checkpoint 2 of 9· Fill the gap
The output below keeps NewProject with a NULL employee and does not include NewEmployee, whose project_id is NULL. Which keyword in the blank produces exactly this result?
SELECT p.project_name, e.employee_name
FROM projects AS p ? OUTER JOIN employees AS e
ON e.project_ID = p.project_ID
ORDER BY p.project_name, e.employee_name;
+------------------+-----------------+
| PROJECT_NAME | EMPLOYEE_NAME |
|------------------+-----------------|
| COVID-19 Vaccine | Maria Inverness |
| COVID-19 Vaccine | Terry Smith |
| Malaria Vaccine | Pat Wang |
| NewProject | NULL |
+------------------+-----------------+A LEFT OUTER JOIN keeps every row of the left table (projects), so NewProject survives with NULL employee columns. Unmatched rows from the right table are dropped, so NewEmployee is missing. RIGHT would keep NewEmployee and drop NewProject. FULL would keep both.
Source: docs.snowflake.com3.Stacking and comparing result sets
Set operators combine whole query results instead of matching rows on a key. They answer different discovery questions. "Give me every order line from both regions" calls for stacking. "Which customer IDs appear in both systems?" and "which appear in CRM but not in billing?" call for comparison.
| Operator | Returns | Duplicates and matching |
|---|---|---|
| UNION (same as UNION DISTINCT) | Rows from both queries | Duplicates eliminated; columns matched by position |
| UNION ALL | Rows from both queries | Duplicates kept; columns matched by position |
| UNION [ALL] BY NAME | Rows from both queries | Columns matched by name; a column missing from one input is filled with NULL |
| INTERSECT | Rows that appear in both results | Duplicates eliminated |
| MINUS / EXCEPT | Rows from the first query that the second does not return | Order of the queries changes the answer |
The difference between UNION and UNION ALL decides row counts. Plain UNION runs a duplicate-elimination step. If two genuine order lines are identical in every column, it keeps only one, and the count comes out low. UNION ALL returns every row from both inputs and skips that step, so it is the right choice whenever identical rows are real records. Use UNION only when you actually want distinct rows. INTERSECT also removes duplicates, and it returns only the overlap, so it can't stack two tables at all.
SELECT postal_code FROM sales_office_postal_example
MINUS
SELECT postal_code FROM customer_postal_example
ORDER BY postal_code;MINUS and EXCEPT are the same operator, and it is not symmetric. The query above returns 94070 and 98116, the office codes with no customer. Put the customer query first and you get 94066 and 98444 instead. To list IDs that exist in CRM but not in billing, the CRM query goes first.
Every query must select the same number of columns, with compatible types and the same meaning in each position (UNION [ALL] BY NAME is the exception). Matching is by position, not by name. SELECT LastName, FirstName ... UNION ALL SELECT FirstName, LastName ... runs without error and quietly puts first names under the LastName heading, because output column names come from the first query. SELECT * on both sides carries the same risk if the tables list their columns in different orders. INTERSECT binds more tightly than UNION [ALL] and MINUS, which are evaluated left to right, so add parentheses whenever you mix operators.
Checkpoint 3 of 9· Match them up
Match each discovery task to the set operator that answers it correctly
Tap a term, then the definition that fits it.
Plain UNION is UNION DISTINCT, so it removes identical rows. Only UNION ALL keeps every row for a full count. INTERSECT returns only the overlap. BY NAME matches columns by name, so tables whose columns are in a different order still line up.
“UNION ALL combines rows by column position without duplicate elimination.”Source: docs.snowflake.com
Checkpoint 4 of 9· Check yourself
An auditor needs the customer IDs that exist in the CRM table but are missing from the billing table. Which query returns them?
MINUS keeps the rows of the first query that the second query does not return, so the CRM query has to come first. Putting billing first gives billing IDs that are missing from CRM. INTERSECT returns the IDs found in both tables.
“Returns the rows returned by the first query that aren’t also returned by the second query.”Source: docs.snowflake.com
Checkpoint 5 of 9· Exam question
A retailer stores EMEA and APAC orders in two tables with identical column lists, orders_emea and orders_apac. An analyst must stack them to count every order line in discovery, and two genuine order lines can be identical in all columns. Which approach returns the correct row count?
Correct answer: B — Combine the two SELECT statements with UNION ALL so every row from both tables is returned and no duplicate-elimination step runs
- A. INTERSECT returns only rows that appear in both inputs, so it would drop nearly all orders instead of stacking them. It is not a way to append two tables.
- B. UNION ALL concatenates the result sets and keeps duplicates, so identical order lines from either region are all counted. It also skips the deduplication work that UNION performs.
- C. MINUS (EXCEPT) returns rows from the first query that are absent from the second. It never appends the second query's rows, so most of the APAC orders would be missing.
- D. UNION removes duplicate rows from the combined result, so two genuinely identical order lines would collapse into one and the count would be too low. Set operators also match columns by position, not by name.
Checkpoint 6 of 9· Exam question
During discovery, an analyst must list customer IDs that exist in the CRM system but have no matching record in billing. Which query returns exactly those IDs?
Correct answer: C — SELECT customer_id FROM crm_customers\nMINUS\nSELECT customer_id FROM billing_accounts
- A. With the operands reversed, this returns billing accounts missing from the CRM, which is the opposite gap. Operand order matters for MINUS.
- B. UNION returns the distinct combined list of customers from both systems, so it does not isolate customers missing from billing.
- C. MINUS returns distinct rows from the first query that do not appear in the second, so placing the CRM query first yields CRM-only customers.
- D. INTERSECT returns customers present in both systems, which is the matched set rather than the unmatched CRM-only customers requested.
Sources4
4.ASOF JOIN: the nearest row in time
Time-series questions such as "what was the quote when this trade happened?" need each left-hand row paired with the single closest row in time on the right. An ordinary join with a range condition returns a row for every right-hand row that satisfies it, which causes fan-out. ASOF JOIN returns exactly one: the right-hand row whose timestamp is closest in the direction the comparison operator points. The syntax keeps the time test in its own clause:
FROM <left_table> ASOF JOIN <right_table>
MATCH_CONDITION ( <left_table.timecol> <comparison_operator> <right_table.timecol> )
[ ON <table.col> = <table.col> [ AND ... ] | USING ( <column_list> ) ]Each clause has strict rules:
MATCH_CONDITIONis required, needs its parentheses, and names the left table's column first. Its operator must be>=,<=,>or<;=is not supported. DATE, TIME, the TIMESTAMP types and NUMBER columns (for example UNIX epoch seconds) are all accepted.ONis optional and holds only equality conditions, which can be joined with AND but never with OR. It groups the rows, for example by stock symbol, before the nearest match in time is chosen.USINGdoes the same job when the key columns have the same name in both tables.- A left row with no qualifying right row is kept, and its right-hand columns are filled with NULLs, as in a left outer join.
- Each ASOF JOIN in a query needs its own
MATCH_CONDITIONdirectly after it. ASOF JOIN cannot be combined with LATERAL.
Putting t.trade_ts >= q.quote_ts inside ON is a syntax error. Move it into MATCH_CONDITION and keep t.symbol = q.symbol in ON.
SELECT *
FROM left_table l ASOF JOIN right_table r
MATCH_CONDITION(l.c3>=r.c3)
ON(l.c1=r.c1 and l.c2=r.c2)
ORDER BY l.c1, l.c2;
+----+----+----------+------+------+------+----------+------+
| C1 | C2 | C3 | C4 | C1 | C2 | C3 | C4 |
|----+----+----------+------+------+------+----------+------|
| A | 1 | 09:15:00 | 3.21 | A | 1 | 09:14:00 | 3.19 |
| A | 2 | 09:16:00 | 3.22 | NULL | NULL | NULL | NULL |
| B | 1 | 09:17:00 | 3.23 | B | 1 | 09:16:00 | 3.04 |
| B | 2 | 09:18:00 | 4.23 | NULL | NULL | NULL | NULL |
+----+----+----------+------+------+------+----------+------+Without ON, all four left rows find a match, and three of them pair with B/1. That is almost never what a per-symbol or per-location analysis means, so leaving out ON is a correctness bug, not a shortcut. Ties are a second hazard. If two right-hand rows have exactly the same timestamp and both qualify, ASOF JOIN still returns only one of them, and which one can change from run to run. When results look unstable, check the right table for duplicate timestamps.
Checkpoint 7 of 9· Fill the gap
This query pairs each left row with the latest right row at or before it in time, within the same (c1, c2) group. Which keyword belongs in the blank so the time comparison is valid?
SELECT *
FROM left_table l ASOF JOIN right_table r
? (l.c3>=r.c3)
ON(l.c1=r.c1 and l.c2=r.c2)
ORDER BY l.c1, l.c2;ASOF JOIN requires the time test (>=, <=, > or <) in MATCH_CONDITION, written directly after the join. ON takes only equality conditions, so it can group the rows but cannot hold the time comparison. USING only lists shared key columns. A WHERE filter would not pick the closest row in time.
Source: docs.snowflake.comCheckpoint 8 of 9· Exam question
A trading analyst has trades(symbol, trade_ts, qty) and quotes(symbol, quote_ts, bid). Each trade must be paired with the latest quote for the same symbol at or before the trade time. This query fails with a syntax error:
SELECT t.symbol, t.trade_ts, q.bid
FROM trades t
ASOF JOIN quotes q
ON t.symbol = q.symbol AND t.trade_ts >= q.quote_ts
What is the correct fix?
Correct answer: C — Move the time comparison into MATCH_CONDITION (t.trade_ts >= q.quote_ts) and keep only the equality on symbol in the ON clause
- A. ASOF JOIN does not accept a range in
ON, andquoteshas nonext_quote_tscolumn anyway. The closest-preceding-row logic comes fromMATCH_CONDITION. - B. ASOF JOIN does not support
USINGto pick a nearest timestamp. The time matching must be expressed inMATCH_CONDITION. - C. ASOF JOIN requires the inequality on the time columns in a separate
MATCH_CONDITIONclause, with theONclause carrying only equality keys such assymbol. With>=, each trade gets the closest quote at or before its timestamp. - D. Exact equality on the timestamp would only match trades and quotes with identical times, which defeats the point-in-time lookup. ASOF JOIN exists specifically to match the closest earlier or later value.
Sources5
5.WHERE, HAVING and QUALIFY: where each filter runs
The three filtering clauses differ by when they run in query evaluation, and that decides what each one can see. In Snowflake, the clauses of a SELECT are typically evaluated in this order:
| Step | Clause | What a filter here can use |
|---|---|---|
| 1 | FROM | Not a filter; builds the rows, including joins |
| 2 | WHERE | Individual row values, before any grouping |
| 3 | GROUP BY | Not a filter; collapses rows into groups |
| 4 | HAVING | Aggregate results such as COUNT or SUM per group |
| 5 | WINDOW | Not a filter; computes window functions |
| 6 | QUALIFY | Window function results |
| 7 | DISTINCT, ORDER BY, LIMIT | Not filters; shape the final output |
Choose the earliest clause that can see what you need to test. A date range or a region code belongs in WHERE, because it removes rows before they are grouped. A test on COUNT(*) > 10 needs HAVING, because the count doesn't exist until grouping is done. A test on a window function's result, such as keeping only the latest row per customer by ROW_NUMBER(), needs QUALIFY. QUALIFY does for window functions what HAVING does for aggregates. It needs at least one window function, either in the SELECT list or in the QUALIFY predicate itself.
WHERE runs before GROUP BY, so no count exists yet when it is evaluated. Move the test to HAVING, which runs after aggregation.
Checkpoint 9 of 9· Check yourself
A CROSS JOIN has paired every warehouse row with every region row, and you only want the pairs where the two region codes are equal. ON is not allowed with CROSS JOIN. Which clause removes the unrelated pairs?
FROM builds the Cartesian product, and WHERE then tests each row's values before any grouping, so it can compare the two region columns. HAVING needs an aggregate and QUALIFY needs a window function, and this query has neither. ON is prohibited for CROSS JOIN.
“A CROSS JOIN can’t be combined with an ON condition clause. However, you can use a WHERE clause to filter the results.”Source: docs.snowflake.com
Sources6
Practise it for real
See how MATCH_CONDITION and the optional ON clause decide ASOF JOIN results, using two small tables
1.Create left_table and right_table with columns c1 VARCHAR(1), c2 TINYINT, c3 TIME and c4 NUMBER(3,2). Insert the four left rows (A/1 09:15, A/2 09:16, B/1 09:17, B/2 09:18) and the two right rows (A/1 09:14, B/1 09:16).
Why: Small, known data lets you check every match by hand.
You should see: SELECT * shows four rows in left_table and two in right_table.
2.Run the ASOF JOIN with MATCH_CONDITION(l.c3>=r.c3) and ON(l.c1=r.c1 and l.c2=r.c2).
Why: ON groups the rows by (c1, c2) before the nearest earlier row is chosen.
You should see: A/1 matches 09:14:00 and B/1 matches 09:16:00. A/2 and B/2 keep their left-hand values, with NULLs in every right-hand column.
3.Run the same query with the ON clause removed.
Why: This shows that, without ON, only the time condition decides the match.
You should see: All four left rows match. A/2, B/1 and B/2 all pair with the right row B/1 at 09:16:00.
4.Move l.c3>=r.c3 into the ON clause instead of MATCH_CONDITION and run it.
Why: This confirms the rule that ON accepts only equality conditions.
You should see: The statement is rejected instead of returning rows.
Stuck? Get a nudge
If the step 3 result surprises you, list the right_table timestamps at or before each left row's c3 and pick the latest one.
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“For each row of o1, a row is produced for each row of o2 that matches according to the ON condition subclause.”
↩︎ Grain: what one row stands for“omitting the ON clause results in a Cartesian product; every row of object_ref1 paired with every row of object_ref2.”
↩︎ Grain: what one row stands for“If the word JOIN is used without specifying INNER or OUTER, then the JOIN is an inner join.”
↩︎ Which rows each join type keeps“A NATURAL JOIN is identical to an explicit JOIN on the common columns of the two tables”
↩︎ Which rows each join type keeps“A CROSS JOIN can’t be combined with an ON condition clause. However, you can use a WHERE clause to filter the results.”
↩︎ Checkpoint - 2.
“each row in the projects table has a unique project ID number”
↩︎ Grain: what one row stands for“An outer join lists all rows in the specified table, even if those rows have no match in the other table.”
↩︎ Which rows each join type keeps - 3.
“In a FROM clause, the LATERAL construct allows an inline view to reference columns from preceding table expressions.”
↩︎ Which rows each join type keeps - 4.
“UNION ALL combines rows by column position without duplicate elimination.”
↩︎ Stacking and comparing result sets“The MINUS and EXCEPT keywords have the same meaning and can be used interchangeably.”
↩︎ Stacking and comparing result sets“Make sure that each query selects the same number of columns”
↩︎ Stacking and comparing result sets“The names of the output columns are based on the names of the columns of the first query.”
↩︎ Stacking and comparing result sets“The INTERSECT operator has higher precedence than UNION [ALL] and MINUS (EXCEPT).”
↩︎ Stacking and comparing result sets“The default is UNION DISTINCT (that is, combine rows by column position with duplicate elimination).”
↩︎ Exam trap 1“Returns the rows returned by the first query that aren’t also returned by the second query.”
↩︎ Exam trap 2“Returns the rows returned by the first query that aren’t also returned by the second query.”
↩︎ Checkpoint - 5.
“the join finds a single row in the second (or right) table that has the closest timestamp value”
↩︎ ASOF JOIN: the nearest row in time“The comparison operator must be one of the following: >=, <=, >, <. The equals operator (=) is not supported.”
↩︎ ASOF JOIN: the nearest row in time“The ON clause cannot contain disjuncts (conditions connected with OR).”
↩︎ ASOF JOIN: the nearest row in time“(ASOF joins are similar to left outer joins in this respect.)”
↩︎ ASOF JOIN: the nearest row in time“The results are non-deterministic because any one of the tying rows might be returned.”
↩︎ ASOF JOIN: the nearest row in time“The comparison operator in the ON clause must be the equal sign (=).”
↩︎ Exam trap 3“If the ON conditions are removed, any combination of values in c1 and c2 may be matched in the final result.”
↩︎ Prediction - 6.
“FROM WHERE GROUP BY HAVING WINDOW QUALIFY DISTINCT ORDER BY LIMIT”
↩︎ WHERE, HAVING and QUALIFY: where each filter runs“QUALIFY does with window functions what HAVING does with aggregate functions and GROUP BY clauses.”
↩︎ WHERE, HAVING and QUALIFY: where each filter runs“The QUALIFY clause requires at least one window function to be specified”
↩︎ WHERE, HAVING and QUALIFY: where each filter runs