Reduce unnecessary work: filters, columns, windows and CTEs
SQL optimization starts by expressing the required result with the smallest logically necessary input and intermediate state.
Your learning goal
Review predicate placement, projection, window partitions and CTE usage without assuming a particular SQL rewrite always runs faster.
Understand the idea
A concrete example
For paid regional revenue, remove cancelled orders and unwanted dates before expensive downstream work when logically valid. The optimizer can push filters and reorder inner joins itself; SQL text order is not proof of physical order.
| Concept | What it means |
|---|---|
| Predicate pushdown | Apply a filter as close to its data source as semantics allow. |
| Projection | Choose the columns a query needs. |
| Window partition | Rows grouped for a window calculation. |
| CTE | A named query expression introduced by WITH. |
Remember: Write the intended result precisely. Compare physical plans and result equivalence before crediting a CTE or predicate rewrite with an improvement.
Explain it step by step · full theory
Learning goals and prerequisites
Review predicate placement, projection, window partitions and CTE usage without assuming a particular SQL rewrite always runs faster.
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.
Filter without changing the question
For paid regional revenue, remove cancelled orders and unwanted dates before expensive downstream work when logically valid. The optimizer can push filters and reorder inner joins itself; SQL text order is not proof of physical order.
Moving predicates across an outer join can change the result. A filter in WHERE can discard the unmatched rows that a LEFT JOIN was meant to preserve. Compare missing keys as well as totals.
Read fewer columns and move fewer bytes
SELECT * can bring wide payloads into scans, joins, sorts and client results. Select only the business fields needed at each stage. Snowflake may already eliminate unused columns, so use Profile to determine what was actually read.
When many fact rows collapse into a small aggregate, aggregating before a join can reduce work if the grouping keys preserve the necessary relationship. It is unsafe when later filters or many-to-many matching require the original row grain.
Optimize a window’s input
ROW_NUMBER needs rows ordered within each partition. Reduce input using filters that belong before the calculation and avoid sorting unrelated columns. Add a stable tie-breaker when dates can tie.
Latest paid order means filter paid first, then rank. Latest order, but only if paid means rank all orders first, then filter. Those are different requirements, not interchangeable optimizations.
Use CTEs for clarity; inspect the plan
A CTE names a subquery, not a promise of persisted storage or an optimization fence. Reuse and optimizer decisions affect the execution plan. Repeating a CTE name does not guarantee the underlying work runs once.
If expensive intermediate output is reused across separate statements, a deliberately materialized temporary table may help, but adds creation work, storage and freshness responsibilities. Measure the complete workflow, not just its last SELECT.
Common mistakes and next action
The filter changes which rows participate in ranking. Preserve the business question.
Write the intended result precisely. Compare physical plans and result equivalence before crediting a CTE or predicate rewrite with an improvement.
Words used in this lesson
- Predicate pushdown
- Apply a filter as close to its data source as semantics allow.
- Projection
- Choose the columns a query needs.
- Window partition
- Rows grouped for a window calculation.
- CTE
- A named query expression introduced by WITH.
See how it works
Choose a step to explore the idea at your own pace.
Open the interactive explanation
Reduce unnecessary work: filters, columns, windows and CTEs
- 6 rows
- 5 available columns
Broad input
Carrying all rows and columns may increase downstream work.
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
- Broad input
Carrying all rows and columns may increase downstream work.
- Unrestricted input: 6 rows; 5 available columns
- Reduce safely
For January paid revenue, retain three rows and only required fields.
- Required January paid input: 101: customer 1, amount 100; 102: customer 2, amount 200; 103: customer 1, amount 150
- Compute result
Join those keys and aggregate; compare the actual physical plan.
- Customer mapping: 1 → west; 2 → east
- Aggregate result: east = 200; west = 250
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
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.
A focused regional query
WITH paid_orders AS (
SELECT CUSTOMER_ID,AMOUNT FROM ORDERS
WHERE STATUS='paid' AND ORDER_DATE>='2026-01-01'::DATE
AND ORDER_DATE<'2026-02-01'::DATE
)
SELECT c.REGION,SUM(p.AMOUNT) AS REVENUE
FROM paid_orders p JOIN CUSTOMERS c ON p.CUSTOMER_ID=c.CUSTOMER_ID
GROUP BY c.REGION ORDER BY c.REGION;What to expect and why
January paid revenue is east 200 and west 250. This clear expression may have the same optimized plan as an equivalent query without a CTE.
| REGION | REVENUE |
|---|---|
| east | 200.00 |
| west | 250.00 |
Latest paid order per customer
SELECT CUSTOMER_ID,ORDER_ID,ORDER_DATE,AMOUNT
FROM ORDERS WHERE STATUS='paid'
QUALIFY ROW_NUMBER() OVER(PARTITION BY CUSTOMER_ID
ORDER BY ORDER_DATE DESC,ORDER_ID DESC)=1
ORDER BY CUSTOMER_ID;What to expect and why
The paid filter applies before ranking. The deterministic selected IDs are 103, 105 and 106.
| CUSTOMER_ID | ORDER_ID | ORDER_DATE | AMOUNT |
|---|---|---|---|
| 1 | 103 | 2026-01-02 | 150.00 |
| 2 | 105 | 2026-02-01 | 80.00 |
| 3 | 106 | 2026-02-02 | 120.00 |
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
Write both interpretations of latest order and explain how a newly cancelled latest order could make them differ.
Compare your reasoning
Write the intended result precisely. Compare physical plans and result equivalence before crediting a CTE or predicate rewrite with an improvement.
Key takeaway
Write the intended result precisely. Compare physical plans and result equivalence before crediting a CTE or predicate rewrite with an improvement.
Connect this lesson to the learning path
By Rohit Ray · Independent educational lesson · Explore this visual lab