Subqueries, correlated queries and semi/anti patterns
A subquery answers a smaller question inside a larger query. EXISTS asks whether a match exists; NOT EXISTS asks whether no match exists.
Understand the idea
Suppose the business asks which customers ordered, not which orders they placed. An ordinary join repeats Asha for each order. EXISTS expresses the actual question and returns her customer row once.
| Concept | What it means |
|---|---|
| Scalar subquery | Returns one value for use in an expression. |
| Correlated subquery | Refers to a row from the outer query. |
| Semi pattern | Keep an outer row if a related row exists. |
| Anti pattern | Keep an outer row if no related row exists. |
A concrete example
Only Asha is returned once, although two orders match.
Remember: Use NOT EXISTS with the relationship condition. It tests absence without multiplying customer rows.
Explain it step by step · full theory
Let us understand the idea
Suppose the business asks which customers ordered, not which orders they placed. An ordinary join repeats Asha for each order. EXISTS expresses the actual question and returns her customer row once.
A correlated EXISTS refers to the current customer ID in its condition. This describes the logical relationship; do not assume Snowflake physically executes the subquery separately for every row. The optimizer can choose another equivalent plan.
Reason through the SQL
A scalar subquery must have a valid single-value result. An ungrouped AVG is one way to obtain that result. A subquery that unexpectedly returns several rows can fail in a scalar position.
NOT IN has a common NULL trap: a NULL in the subquery can make comparisons unknown. Use NOT EXISTS for the no-match question and explicitly define how NULL keys should behave. Correlated scalar subqueries have Snowflake support restrictions; EXISTS or a join is often clearer.
Words used in this lesson
- Scalar subquery
- Returns one value for use in an expression.
- Correlated subquery
- Refers to a row from the outer query.
- Semi pattern
- Keep an outer row if a related row exists.
- Anti pattern
- Keep an outer row if no related row exists.
See how it works
Choose a step to explore the idea at your own pace.
Open the interactive explanation
Subqueries, correlated queries and semi/anti patterns
Begin with the question
A subquery answers a smaller question inside a larger query. EXISTS asks whether a match exists; NOT EXISTS asks whether no match exists.
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
- Begin with the question
A subquery answers a smaller question inside a larger query. EXISTS asks whether a match exists; NOT EXISTS asks whether no match exists.
- Choose the operation
Suppose the business asks which customers ordered, not which orders they placed. An ordinary join repeats Asha for each order. EXISTS expresses the actual question and returns her customer row once.
- Check the meaning
Use NOT EXISTS with the relationship condition. It tests absence without multiplying customer rows.
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.
- No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
- 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.
- 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. - 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
Read first, then run manually in an authorized Snowflake learning session with a warehouse. Each WITH/VALUES example includes its own inputs and creates no stored tables. Expected results are illustrative, not live execution.
Customers who ordered
WITH customers AS (
SELECT COLUMN1 AS CUSTOMER_ID, COLUMN2 AS NAME
FROM VALUES (1,'Asha'),(2,'Ben'),(3,'Chen')
), orders AS (
SELECT COLUMN1 AS ORDER_ID, COLUMN2 AS CUSTOMER_ID, COLUMN3 AS AMOUNT
FROM VALUES (101,1,40),(102,1,60),(103,4,25)
)
SELECT c.NAME FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.CUSTOMER_ID=c.CUSTOMER_ID)
ORDER BY c.CUSTOMER_ID;What to expect and why
Only Asha is returned once, although two orders match.
Customers with no orders
WITH customers AS (
SELECT COLUMN1 AS CUSTOMER_ID, COLUMN2 AS NAME
FROM VALUES (1,'Asha'),(2,'Ben'),(3,'Chen')
), orders AS (
SELECT COLUMN1 AS ORDER_ID, COLUMN2 AS CUSTOMER_ID, COLUMN3 AS AMOUNT
FROM VALUES (101,1,40),(102,1,60),(103,4,25)
)
SELECT c.NAME FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.CUSTOMER_ID=c.CUSTOMER_ID)
ORDER BY c.CUSTOMER_ID;What to expect and why
Ben and Chen are returned. An unrelated order for customer 4 does not change this answer.
Orders above the overall average
WITH customers AS (
SELECT COLUMN1 AS CUSTOMER_ID, COLUMN2 AS NAME
FROM VALUES (1,'Asha'),(2,'Ben'),(3,'Chen')
), orders AS (
SELECT COLUMN1 AS ORDER_ID, COLUMN2 AS CUSTOMER_ID, COLUMN3 AS AMOUNT
FROM VALUES (101,1,40),(102,1,60),(103,4,25)
)
SELECT ORDER_ID, AMOUNT FROM orders
WHERE AMOUNT > (SELECT AVG(AMOUNT) FROM orders) ORDER BY ORDER_ID;What to expect and why
The average is 125/3, approximately 41.67. Only order 102 with amount 60 is above it.
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
Explain why Asha appears once with EXISTS but twice in an ordinary join.
Compare your reasoning
EXISTS is a yes/no test applied to the customer row. The ordinary join emits one pair for each of her two orders.