What you will be able to do
- Structure a query with CTEs and with correlated or uncorrelated subqueries, and know where Snowflake allows each
- Choose a fixed-depth self-join, a recursive CTE or CONNECT BY for a parent/child tree, and explain how recursion stops
- Keep column types consistent when appending sources or building recursive queries
- Choose row or block sampling, use SEED, and use APPROX_COUNT_DISTINCT when an estimate is good enough
1.Structuring queries with CTEs and subqueries
A CTE (common table expression) is a named subquery declared in a WITH clause. It acts as a temporary view that exists only for the statement that defines it. Breaking a long query into named steps, such as a cleaned source, then a ranked set, then a final filter, makes it more modular and easier to maintain. Be careful with names, though. A CTE that shares a name with a table or view takes precedence over that object, so WITH orders AS (...) silently hides the real orders table for the rest of the statement. Avoid names that match tables, views or SQL functions.
Subqueries come in two independent pairs. Correlated or uncorrelated describes whether the subquery references a column from the outer query. An uncorrelated subquery runs once and hands its result to the outer query. A correlated subquery behaves as if it ran for every outer row. Scalar or non-scalar describes the shape of the result. A scalar subquery returns one value, or NULL when no rows qualify. A non-scalar subquery returns zero or more rows, and when nothing qualifies it returns zero rows, not NULLs.
SELECT p.name, p.annual_wage, p.country FROM pay AS p WHERE p.annual_wage < (SELECT MAX(per_capita_GDP) FROM international_GDP i WHERE p.country = i.name);The MAX in that query is there for a structural reason, not for the maths. international_GDP has one row per country, but the server can't know that, and a scalar subquery must return no more than one row. Wrapping the column in MAX (or MIN, or AVG) guarantees a single value without changing it. The uncorrelated version, which compares every wage to Brazil's GDP, needs no aggregate and runs only once. Placement matters too. Uncorrelated scalar subqueries can go anywhere a value expression can, but correlated scalar subqueries are supported only in WHERE. EXISTS, ANY/ALL and IN subqueries can be either kind, also in WHERE.
Checkpoint 1 of 5· Fill the gap
This query should list jobs paid less than the per-capita GDP of the job's own country. Which expression completes the subquery?
SELECT p.name, p.annual_wage, p.country FROM pay AS p WHERE p.annual_wage < (SELECT MAX(per_capita_GDP) FROM international_GDP i WHERE ? = i.name);The subquery must refer to the outer row's p.country. That makes it a correlated subquery, evaluated as if once per job, so each wage is compared with its own country's GDP. A constant such as 'Brazil' would make it the uncorrelated version, which compares every wage with a single country.
Source: docs.snowflake.comCheckpoint 2 of 5· Check yourself
A non-scalar subquery that can return several rows finds no rows that match its filter. What does it return?
Only a scalar subquery returns NULL when no rows qualify. A non-scalar subquery returns zero rows, not NULLs.
“If no rows qualify to be returned, the subquery returns 0 rows (not NULLs).”Source: docs.snowflake.com
2.Hierarchies: self-joins, recursive CTEs and CONNECT BY
Org charts and parts explosions are trees, and they are often stored in a single table where each row points to its parent. In employees (title, employee_ID, manager_ID), the President's manager_ID is NULL and every other row's manager_ID holds another employee's ID. That self-referencing parent key is the input to every technique below. Constraints on such keys are covered in Foreign keys and parent/child relationships.
When the depth is fixed and known, a self-join is enough. Joining employees AS emps to employees AS mgrs on emps.manager_ID = mgrs.employee_ID pairs every employee with their manager, and a LEFT OUTER JOIN keeps the President. Each extra level needs another join, though, so when the company adds a level, the query has to be rewritten.
A recursive CTE walks a tree of unknown depth. Its body is an anchor clause, UNION ALL, then a recursive clause, and it runs in this order:
- The anchor runs once and selects the top of the tree, here
WHERE title = 'President'. It can't reference the CTE's own name. Its rows go to both the final result and a working table. - The recursive clause joins the source table to the CTE name, which reads the working table, and so returns the next level down.
- That output is added to the final result and replaces the working table. The working table only ever holds the most recent level.
- Steps 2 and 3 repeat until an iteration returns no rows.
The recursive clause is limited to projections, joins and filters. Aggregates, window functions, GROUP BY, ORDER BY, LIMIT and DISTINCT are not allowed in it.
SELECT '' AS indent, -- Line 6
employee_ID, -- Line 7
manager_ID, -- Line 8
title AS employee_title -- Line 9
FROM employees -- Line 10
WHERE title = 'President' -- Line 11
-- Line 12
UNION ALL -- Line 13
-- Line 14
SELECT indent || '--- ', -- Line 15
employees.employee_ID, -- Line 16
employees.manager_ID, -- Line 17
employees.title -- Line 18
FROM employees JOIN managers -- Line 19
ON employees.manager_ID = managers.employee_ID -- Line 20A badly built recursive CTE can loop forever. The query keeps running until it times out under STATEMENT_TIMEOUT_IN_SECONDS or someone cancels it. One common cause is column order. The anchor's and the recursive clause's projection lists must both match the CTE's column list position for position, and a swapped pair, such as manager_ID where employee_ID belongs, can keep producing rows.
CONNECT BY is the other option for unknown depth. It starts from rows chosen by START WITH and processes the tree one level at a time, using PRIOR to mark which values come from the level above. It provides pseudo-columns such as LEVEL and CONNECT_BY_ROOT, and SYS_CONNECT_BY_PATH builds the root-to-row path.
SELECT indent(LEVEL) || employee_ID, manager_ID, title
FROM employees
-- This sub-clause specifies the record at the top of the hierarchy,
-- but does not allow additional derived fields, such as the sort key.
START WITH TITLE = 'President'
CONNECT BY ...| Technique | Wins when | Limitation |
|---|---|---|
| Self-join (one join per level) | The number of levels is fixed and known | The query must change when the depth changes |
| Recursive CTE | You need to join other tables, or add derived columns such as a sort_key in the anchor | Every column must be listed, and anchor and recursive projections must match the CTE columns |
| CONNECT BY / START WITH | A self-join with all columns available, plus LEVEL and SYS_CONNECT_BY_PATH | Allows only self-joins, and START WITH can't add derived columns |
Check a hierarchy before you trust the walk. Both techniques assume a contiguous tree. If the VP of Engineering's record is deleted, the Programmer and QA Engineer still point to ID 10, but no path from the President reaches them, so they drop out of the result without any error. A single table can hold several trees, but you can query only one tree at a time, and that tree must be contiguous.
Checkpoint 3 of 5· Match them up
Match each hierarchy requirement to the technique that fits it best.
Tap a term, then the definition that fits it.
Self-joins work when the depth is fixed and known, but each new level means rewriting the query. For unknown depth, CONNECT BY gives you all columns and pseudo-columns like LEVEL, but it allows only self-joins. Joining the hierarchy to another table therefore needs a recursive CTE.
“CONNECT BY allows only self-joins. Recursive CTEs are more flexible and allow a table to be joined to one or more other tables.”Source: docs.snowflake.com
3.Appending, scaffolding and casting to one consistent type
Enrichment often means appending one source to another or filling gaps in a base set. A recursive CTE already does this, because UNION ALL stacks each new level under the rows before it. The same pattern adds an external source to a base set, and it works only when both sides have the same shape: the same number of columns, in the same order, with compatible types. How the set operators treat duplicates is covered in [Set operators: UNION [ALL], INTERSECT, MINUS/EXCEPT](lesson:1.2). For gaps, a CROSS JOIN can build a scaffold, such as every date in a range or every product × region pair, and the facts are then left-joined onto it, so missing combinations appear as rows instead of vanishing. Which rows each join keeps is in Join types: which rows survive.
Casting is what makes those shapes line up. Explicit CAST and the TRY_ variants are taught in Casting and TRY_ conversion. In this lesson's queries, type mismatches show up in three places:
- Recursive CTEs: the anchor and the recursive clause must project matching columns. In the indent example, the anchor's
''and the recursive clause'sindent || '--- 'are both strings for the same column. - Values from VARIANT: in the
ROW_NUMBERlateral query on the window-functions page,f.value:completed_onis returned with its JSON quotes, for example"2024-06-03T20:17:08.621001019Z". Cast it to a timestamp before you present it or compare it with real dates. - RANGE frames: an explicit-offset
RANGEframe accepts only a numeric, date or timestampORDER BYvalue, so a date held asVARCHARmust be cast before it can drive a time-distance window.
CREATE OR REPLACE TABLE sum_example (k INT, d DECIMAL(10,5),
s1 VARCHAR(10), s2 VARCHAR(10));SUM(s1) on that VARCHAR column still returns a number (23.2), because Snowflake converts the text implicitly. The two columns' sums differ (22.3 against 23.2) only because one row holds 9 in d and '9.9' in s1. The data differs, not the conversion. The practical lesson is that an aggregate over text can succeed without a warning, so cast to the intended numeric type yourself and the result will display, compare and union the same way every time.
Checkpoint 4 of 5· Check yourself
Your orders table stores order_date as VARCHAR text such as '2024-06-03'. You need a 7-day moving total, so you write SUM(amount) OVER (ORDER BY order_date RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW). What is the right fix?
An explicit-offset RANGE frame accepts only one ORDER BY expression, and it must be a NUMBER, DATE or timestamp type, so the VARCHAR date has to be cast first. A ROWS frame would count 7 rows, not 7 days. A second ORDER BY column isn't allowed in this kind of frame.
“TIME and other Snowflake data types are not supported when this type of window frame is used.”Source: docs.snowflake.com
4.Sampling and approximate distinct counts
On very large tables, an exact answer is often slower than the question deserves. SAMPLE (or its synonym TABLESAMPLE) returns a random subset of rows. You can ask for a fraction or for a fixed number of rows. A fixed number returns exactly that many rows unless the table has fewer. A fraction returns a count that depends on the table's size and the probability you give.
samplingMethod ::= { { BERNOULLI | ROW } ( { <probability> | <num> ROWS } ) | { SYSTEM | BLOCK } ( <probability> ) [ { REPEATABLE | SEED } ( <seed> ) ] }The two methods differ in what each coin flip covers. BERNOULLI (or ROW), the default, includes each row with probability p/100. SYSTEM (or BLOCK) flips one coin for each block of rows and keeps or drops the whole block. Block sampling can't do fixed-size samples, so SAMPLE BLOCK (100 ROWS) is invalid. Adding SEED (or REPEATABLE) makes the sample deterministic, which you need when a colleague must reproduce your validation. For shuffling rows or assigning random A/B groups instead of sampling, the random-value functions are covered in GENERATOR, SEQ, UNIFORM and RANDOM.
Approximation answers a different question: you scan all the data but use a cheaper algorithm. APPROX_COUNT_DISTINCT (alias HLL) uses HyperLogLog to estimate COUNT(DISTINCT ...). It works as an aggregate or as a window function, and its OVER clause takes only PARTITION BY. Use it when a dashboard needs distinct visitors on billions of rows and a close estimate is acceptable. Keep COUNT(DISTINCT ...) when the figure must be exact, such as a reconciliation total. A related family, HLL_ACCUMULATE, HLL_COMBINE and HLL_ESTIMATE, works with the intermediate HyperLogLog state, so stored daily states can be combined into larger periods.
Checkpoint 5 of 5· Check yourself
Two queries run over billions of rows. One feeds a dashboard of distinct daily visitors where a close estimate is fine. The other produces a distinct-customer total that must match the finance ledger exactly. Which pairing is right?
HyperLogLog trades a small error for speed and low memory, which suits a dashboard on very large input. A figure that must reconcile exactly needs COUNT(DISTINCT ...).
“We recommend using HyperLogLog whenever the input is potentially large and an approximate result is acceptable.”Source: docs.snowflake.com
Practise it for real
Load a small employee/manager table and walk it with both a fixed-depth self-join and a recursive CTE.
1.Create
employees (title VARCHAR, employee_ID INTEGER, manager_ID INTEGER)and insert the six rows: President (1, NULL), Vice President Engineering (10, 1), Programmer (100, 10), QA Engineer (101, 10), Vice President HR (20, 1), Health Insurance Analyst (200, 20).Why: A single table with a self-referencing manager_ID is the input every hierarchical technique reads.
You should see: Six rows, with only the President having a NULL manager_ID.
2.Run a LEFT OUTER JOIN of
employees AS empstoemployees AS mgrsonemps.manager_ID = mgrs.employee_ID, ordered bymgrs.employee_ID NULLS FIRST.Why: This shows what a fixed-depth self-join gives you: each employee next to one manager, with no sense of depth.
You should see: Six rows. The President has a NULL manager title.
3.Run the recursive CTE
WITH RECURSIVE managers (indent, employee_ID, manager_ID, employee_title), with an anchor ontitle = 'President'and a recursive clause joiningemployeestomanagers, then selectindent || employee_title.Why: The anchor seeds the working table, and each iteration adds the next level until nothing new comes back.
You should see: Six rows, indented by level: no prefix for the President, '--- ' for the VPs and '--- --- ' for their reports.
4.Delete the Vice President Engineering row (employee_ID 10) and rerun the recursive CTE.
Why: This shows that recursion only follows a contiguous tree.
You should see: Three rows: the President, the VP HR and the Health Insurance Analyst. The Programmer and QA Engineer are gone, with no error.
Stuck? Get a nudge
If the recursive query never finishes, check that the anchor and recursive SELECT lists are in the same column order as the CTE's column list.
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.snowflake.com/en/user-guide/queries-cteOfficial docs
“A CTE (common table expression) is a named subquery defined in a WITH clause.”
↩︎ Structuring queries with CTEs and subqueries“If a query defines a CTE with a particular name, the CTE takes precedence over tables, etc.”
↩︎ Structuring queries with CTEs and subqueries“The working table contains only the result of the most recent iteration.”
↩︎ Hierarchies: self-joins, recursive CTEs and CONNECT BY“Aggregate or window functions. GROUP BY, ORDER BY, LIMIT, or DISTINCT.”
↩︎ Hierarchies: self-joins, recursive CTEs and CONNECT BY - 2.
“the server requires that the subquery return no more than one row”
↩︎ Structuring queries with CTEs and subqueries“Correlated scalar subqueries in WHERE clauses.”
↩︎ Structuring queries with CTEs and subqueries“A scalar subquery returns a single value (one column of one row). If no rows qualify to be returned, the subquery returns NULL.”
↩︎ Exam trap 3“If no rows qualify to be returned, the subquery returns 0 rows (not NULLs).”
↩︎ Checkpoint - 3.
“But if the number of levels changes, the queries need to change.”
↩︎ Hierarchies: self-joins, recursive CTEs and CONNECT BY“in CONNECT BY you use the keyword PRIOR to indicate which column values should be taken from the previous iteration”
↩︎ Hierarchies: self-joins, recursive CTEs and CONNECT BY“you can only query one tree at a time, and that tree must be contiguous.”
↩︎ Hierarchies: self-joins, recursive CTEs and CONNECT BY“If the order of the columns in the various projection clauses does not match, you can cause problems such as infinite loops.”
↩︎ Appending, scaffolding and casting to one consistent type“CONNECT BY allows only self-joins. Recursive CTEs are more flexible and allow a table to be joined to one or more other tables.”
↩︎ Exam trap 2“CONNECT BY allows only self-joins. Recursive CTEs are more flexible and allow a table to be joined to one or more other tables.”
↩︎ Checkpoint - 4.
“If expr2 is a TIMESTAMP data type, n must be an INTERVAL constant.”
↩︎ Appending, scaffolding and casting to one consistent type“TIME and other Snowflake data types are not supported when this type of window frame is used.”
↩︎ Checkpoint - 5.
“BERNOULLI (or ROW): Includes each row with a probability of p/100.”
↩︎ Sampling and approximate distinct counts“You can specify a seed to make the sampling deterministic.”
↩︎ Sampling and approximate distinct counts“SYSTEM (or BLOCK): Includes each block of rows with a probability of p/100.”
↩︎ Exam trap 1 - 6.
“Uses HyperLogLog to return an approximation of the distinct cardinality of the input”
↩︎ Sampling and approximate distinct counts“HLL_ACCUMULATE , HLL_COMBINE , HLL_ESTIMATE”
↩︎ Sampling and approximate distinct counts - 7.
“We recommend using HyperLogLog whenever the input is potentially large and an approximate result is acceptable.”
↩︎ Sampling and approximate distinct counts