Most Snowflake SQL we review is correct but verbose: nested subqueries to pick the latest row, self-joins to find gaps, and hand-rolled sessionization in Python. Snowflake has several SQL features that remove that code. This tutorial covers four of them: QUALIFY, MATCH_RECOGNIZE, ASOF JOIN, and GROUP BY ALL/SELECT * EXCLUDE. Each example uses a small, made-up schema so you can run it in a worksheet.
Sample data
CREATE OR REPLACE TABLE events (
user_id NUMBER, event_ts TIMESTAMP_NTZ, event_type STRING, amount NUMBER(10,2)
);
CREATE OR REPLACE TABLE prices (
symbol STRING, price_ts TIMESTAMP_NTZ, price NUMBER(10,2)
);
CREATE OR REPLACE TABLE trades (
symbol STRING, trade_ts TIMESTAMP_NTZ, qty NUMBER
);
1. QUALIFY: filter on window functions directly
The classic "latest row per key" pattern uses a subquery just to filter on ROW_NUMBER(). QUALIFY is to window functions what HAVING is to aggregates.
-- Latest event per user
SELECT *
FROM events
QUALIFY ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY event_ts DESC) = 1;
It is also the cleanest way to deduplicate during loads:
CREATE OR REPLACE TABLE events_dedup AS
SELECT *
FROM events
QUALIFY ROW_NUMBER() OVER (
PARTITION BY user_id, event_ts, event_type
ORDER BY amount DESC NULLS LAST) = 1;
Tips:
- Always make the
ORDER BYdeterministic. If two rows tie, which one wins is arbitrary. - You can use
QUALIFYwithout putting the window function in the select list. - Evaluation order is
WHERE, thenGROUP BY/HAVING, then window functions, thenQUALIFY. Filter early withWHEREso the window sorts less data.
2. MATCH_RECOGNIZE: row pattern matching
MATCH_RECOGNIZE finds sequences of rows that match a regex-like pattern. It suits funnels, sessionization, and detecting runs. Here we find users who viewed a product, added to cart, and then purchased, in that order, with anything in between:
SELECT *
FROM events
MATCH_RECOGNIZE (
PARTITION BY user_id
ORDER BY event_ts
MEASURES
MATCH_NUMBER() AS match_no,
FIRST(view.event_ts) AS viewed_at,
LAST(purchase.event_ts) AS purchased_at,
SUM(purchase.amount) AS revenue
ONE ROW PER MATCH
AFTER MATCH SKIP PAST LAST ROW
PATTERN (view any_event* cart any_event* purchase)
DEFINE
view AS event_type = 'view',
cart AS event_type = 'add_to_cart',
purchase AS event_type = 'purchase'
);
Notes:
- Pattern variables not listed in
DEFINE(such asany_event) match any row. ONE ROW PER MATCHreturns a summary row.ALL ROWS PER MATCHreturns every matched row, andCLASSIFIER()tells you which variable each row matched.AFTER MATCH SKIP PAST LAST ROWprevents overlapping matches.- Unbounded patterns like
any_event*can be expensive on very large partitions. Partition by a selective key and filter by date first.
A second use is session detection: a new session starts after a 30-minute gap.
SELECT user_id, session_no, MIN(event_ts) AS session_start, COUNT(*) AS events
FROM (
SELECT user_id, event_ts,
SUM(new_session) OVER (PARTITION BY user_id ORDER BY event_ts) AS session_no
FROM (
SELECT user_id, event_ts,
IFF(DATEDIFF('minute',
LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts),
event_ts) > 30
OR LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts) IS NULL,
1, 0) AS new_session
FROM events))
GROUP BY ALL;
This window-function version is a good baseline to compare against a MATCH_RECOGNIZE rewrite. For simple gap logic it is often the shorter of the two. Reach for MATCH_RECOGNIZE when the pattern is truly a sequence.
3. ASOF JOIN: point-in-time lookups
Joining each trade to the most recent price at or before the trade time used to need a range join plus QUALIFY. ASOF JOIN does it directly:
SELECT t.symbol, t.trade_ts, t.qty, p.price_ts, p.price
FROM trades t
ASOF JOIN prices p
MATCH_CONDITION (t.trade_ts >= p.price_ts)
ON t.symbol = p.symbol;
MATCH_CONDITIONtakes a single inequality (>=,>,<=,<). With>=, each left row gets the closest right row at or before it.- The
ONclause holds the equality keys. - Left rows with no match are dropped with
ASOF JOIN. UseLEFT ASOF JOINto keep them.
Typical uses are SCD-style lookups, IoT readings against configuration history, and financial tick data.
4. Smaller quality-of-life features
-- Group by every non-aggregate column in the select list
SELECT user_id, event_type, COUNT(*) AS n, SUM(amount) AS total
FROM events
GROUP BY ALL;
-- Select everything except noisy columns
SELECT * EXCLUDE (amount) FROM events;
-- Rename while selecting all
SELECT * RENAME (event_ts AS occurred_at) FROM events;
-- Reuse column aliases within the same SELECT
SELECT amount * 1.2 AS gross, gross - amount AS tax FROM events;
GROUP BY ALL is excellent for ad hoc analysis. In production models, an explicit column list is easier to review, so weigh readability before using it there.
Checking performance
After rewriting a query, compare it against the old version in the Query Profile. Look at bytes scanned, partitions scanned versus total, and spilling. Cleaner SQL does not automatically mean faster SQL. QUALIFY and ASOF JOIN mostly save code, while MATCH_RECOGNIZE can save a lot of engineering effort but needs sensible partitioning.
Checklist
- Replace "subquery + ROW_NUMBER = 1" with
QUALIFYand a deterministicORDER BY. - Use
MATCH_RECOGNIZEfor ordered, multi-step behavior and keep partitions selective. - Use
ASOF JOINfor latest-as-of lookups instead of range joins. - Use
GROUP BY ALLandEXCLUDEin exploration, and be explicit in shared models. - Validate results on a sample against the old query before switching over, and check the Query Profile.
Need a hand modernizing a large SQL codebase or reviewing a Snowflake migration? PowderInsights' senior Snowflake developers and architects can help. Get in touch with your scope and timeline.