In this post we are going to cover MATCH_RECOGNIZE in Snowflake.
MATCH_RECOGNIZE is a regular expression over rows instead of characters. We put the rows in order, give a name to each kind of row we care about, and then write a pattern over those names. Snowflake walks the rows in order and hands us back every stretch of them that fits.
We will start by answering one question the ordinary way, with LAG and CASE, so that we have something to check every match against by eye. Then we will build the same answer with a pattern, grow the pattern one character at a time, look at the rows inside each match, and finish by looking for a shape rather than a direction.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 62 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's answer it the boring way first
- Let's write the smallest useful pattern
- Now let's turn a pair into a run
- Now let's see the rows inside each match
- Now let's be specific about how many
- Now let's look for a shape: a dip and a recovery
- What does the NULL do?
- Now let's restart the pattern with PARTITION BY
- Can a symbol with no definition match anything?
Let's create some sample data
Pattern matching needs something with an order to it. So every query on this page reads the same monthly revenue series: ORDERS grouped into months.
It is the series from Episode 52, rebuilt in a CTE called M. Run the setup once.
-- ORDERS comes from the setup script this course uses throughout.
-- Run it once; every episode reuses the same tables.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
-- Every query on this page reads one monthly series, built in a CTE called M
-- so you can paste any of them straight into a worksheet.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START,
SUM(AMOUNT) AS TOTAL
FROM ORDERS
GROUP BY 1
)
SELECT * FROM M ORDER BY MONTH_START;Let's look at the series we are going to work with.
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START,
COUNT(*) AS N_ORDERS, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1 ORDER BY 1;| MONTH_START | N_ORDERS | TOTAL |
|---|---|---|
| 2023-01-01 | 2 | 5090.50 |
| 2023-02-01 | 2 | 7650.00 |
| 2023-03-01 | 2 | 7330.75 |
| 2023-04-01 | 2 | 9010.00 |
| 2023-05-01 | 2 | 3980.25 |
| 2023-06-01 | 2 | 10075.50 |
| 2023-07-01 | 2 | 7170.00 |
| 2023-08-01 | 2 | 12110.00 |
| 2023-09-01 | 1 | 5540.00 |
| 2023-10-01 | 2 | 8445.00 |
| 2023-11-01 | 2 | 11380.00 |
| 2023-12-01 | 2 | 8980.00 |
| 2024-01-01 | 2 | 15110.00 |
| 2024-02-01 | 1 | 8340.00 |
| 2024-03-01 | 2 | 2930.00 |
| 2024-04-01 | 2 | 12640.00 |
| 2024-05-01 | 2 | 16875.00 |
| 2024-06-01 | 2 | 11660.00 |
| 2024-07-01 | 1 | 8820.00 |
| 2024-08-01 | 2 | 15640.00 |
| 2024-09-01 | 2 | 7010.00 |
| 2024-10-01 | 1 | 9640.00 |
| 2024-11-01 | 1 | NULL |
23 months, with a total per month and the number of orders behind it.
Two things about this grid matter later. The order is the only reason any pattern on this page means anything. And November 2024, the final month in the series, has a TOTAL of NULL.
Let's answer it the boring way first
The question for most of this page is “when did revenue rise?”. We already know how to write that. LAG gives us the previous month and a CASE labels each month up, down or the same.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
LAG(TOTAL) OVER (ORDER BY MONTH_START) AS PREV_TOTAL,
CASE WHEN TOTAL > LAG(TOTAL) OVER (ORDER BY MONTH_START) THEN 'UP'
WHEN TOTAL < LAG(TOTAL) OVER (ORDER BY MONTH_START) THEN 'DOWN'
WHEN TOTAL = LAG(TOTAL) OVER (ORDER BY MONTH_START) THEN 'SAME'
END AS DIRECTION
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | PREV_TOTAL | DIRECTION |
|---|---|---|---|
| 2023-01-01 | 5090.50 | NULL | NULL |
| 2023-02-01 | 7650.00 | 5090.50 | UP |
| 2023-03-01 | 7330.75 | 7650.00 | DOWN |
| 2023-04-01 | 9010.00 | 7330.75 | UP |
| 2023-05-01 | 3980.25 | 9010.00 | DOWN |
| 2023-06-01 | 10075.50 | 3980.25 | UP |
| 2023-07-01 | 7170.00 | 10075.50 | DOWN |
| 2023-08-01 | 12110.00 | 7170.00 | UP |
| 2023-09-01 | 5540.00 | 12110.00 | DOWN |
| 2023-10-01 | 8445.00 | 5540.00 | UP |
| 2023-11-01 | 11380.00 | 8445.00 | UP |
| 2023-12-01 | 8980.00 | 11380.00 | DOWN |
| 2024-01-01 | 15110.00 | 8980.00 | UP |
| 2024-02-01 | 8340.00 | 15110.00 | DOWN |
| 2024-03-01 | 2930.00 | 8340.00 | DOWN |
| 2024-04-01 | 12640.00 | 2930.00 | UP |
| 2024-05-01 | 16875.00 | 12640.00 | UP |
| 2024-06-01 | 11660.00 | 16875.00 | DOWN |
| 2024-07-01 | 8820.00 | 11660.00 | DOWN |
| 2024-08-01 | 15640.00 | 8820.00 | UP |
| 2024-09-01 | 7010.00 | 15640.00 | DOWN |
| 2024-10-01 | 9640.00 | 7010.00 | UP |
| 2024-11-01 | NULL | 9640.00 | NULL |
This grid is the control for the whole post. Everything MATCH_RECOGNIZE finds has to agree with the DIRECTION column, and we can check it by eye.
Let's count that column so we have the numbers to hand.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
), D AS (
SELECT CASE WHEN TOTAL > LAG(TOTAL) OVER (ORDER BY MONTH_START) THEN 'UP'
WHEN TOTAL < LAG(TOTAL) OVER (ORDER BY MONTH_START) THEN 'DOWN'
WHEN TOTAL = LAG(TOTAL) OVER (ORDER BY MONTH_START) THEN 'SAME'
END AS DIRECTION
FROM M
)
SELECT COUNT(*) AS MONTHS,
COUNT_IF(DIRECTION = 'UP') AS UP_MONTHS,
COUNT_IF(DIRECTION = 'DOWN') AS DOWN_MONTHS,
COUNT_IF(DIRECTION IS NULL) AS UNDECIDED
FROM D;| MONTHS | UP_MONTHS | DOWN_MONTHS | UNDECIDED |
|---|---|---|---|
| 23 | 11 | 10 | 2 |
23 months: 11 up, 10 down, and 2 that cannot be called either way. Both of the undecided months are in the LAG and CASE grid, and each one is undecided for its own reason.
- January 2023 — the earliest month in the series, with no
PREV_TOTALto compare against. - November 2024 — the final month, whose own
TOTALisNULL, so every comparison involving it is unknown.
Hold on to the 11. It is the number of months that rose, and we are going to arrive at it again from a completely different direction once we start looking at the rows inside each match.
Let's write the smallest useful pattern
MATCH_RECOGNIZE goes after a table or subquery in FROM. It holds five clauses that do five separate jobs.
Let's put them all to work on the smallest pattern worth writing: a row, followed by a row that is higher than it.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(MONTH_START) AS FROM_MONTH,
LAST(MONTH_START) AS TO_MONTH,
COUNT(*) AS ROWS_IN_MATCH
ONE ROW PER MATCH
PATTERN (A B)
DEFINE B AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO;| MATCH_NO | FROM_MONTH | TO_MONTH | ROWS_IN_MATCH |
|---|---|---|---|
| 1 | 2023-01-01 | 2023-02-01 | 2 |
| 2 | 2023-03-01 | 2023-04-01 | 2 |
| 3 | 2023-05-01 | 2023-06-01 | 2 |
| 4 | 2023-07-01 | 2023-08-01 | 2 |
| 5 | 2023-09-01 | 2023-10-01 | 2 |
| 6 | 2023-12-01 | 2024-01-01 | 2 |
| 7 | 2024-03-01 | 2024-04-01 | 2 |
| 8 | 2024-07-01 | 2024-08-01 | 2 |
| 9 | 2024-09-01 | 2024-10-01 | 2 |
ORDER BY— what in sequence means. Everything else is defined relative to this order.MEASURES— what you get back about each match.MATCH_NUMBER()numbers the matches, andFIRST,LASTandCOUNTread across the rows the match contains.ONE ROW PER MATCH— the shape of the output: one summary row per match rather than the member rows.PATTERN— the regular expression, written over symbol names rather than characters.DEFINE— what each symbol means, as an ordinary boolean expression.
9 matches, each exactly two months, and each pair is a month followed by a higher month. January to February, March to April, and so on.
Check any of them against the DIRECTION column in the LAG and CASE grid. The second month of every pair is an UP month.
A was never defined, and that is deliberate
DEFINE names only B. A has no definition at all, which means it matches any row. It is just “the row the climb starts from”.
We will prove that is what an undefined symbol does at the end of the post, with a pattern in which nothing can fail.
In DEFINE, use LAG. PREV() is the function you would reach for, it exists, and Snowflake allows it only in MEASURES — the documentation says so some ten paragraphs in. Write it in DEFINE and the answer is a bare Unknown function PREV., which tells you nothing about the rule being enforced. (That refusal is not captured on this page; the only error pane here is the one where we leave ORDER BY out.)
Two more rules worth knowing before you spend time on them, both learned from the engine rather than guessed: START is a reserved word and cannot be used as a pattern symbol name, and ONE ROW PER MATCH with no PARTITION BY and no MEASURES has nothing to return at all — every match query needs at least one measure.
Now let's turn a pair into a run
A pair of months is not usually the question. “How long did the climb last?” is.
In a regular expression that is one character. B+ means one or more Bs. Let's change nothing else.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(MONTH_START) AS FROM_MONTH,
LAST(MONTH_START) AS TO_MONTH,
COUNT(*) AS MONTHS_IN_RUN,
FIRST(TOTAL) AS STARTED_AT,
LAST(TOTAL) AS ENDED_AT
ONE ROW PER MATCH
PATTERN (A B+)
DEFINE B AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO;| MATCH_NO | FROM_MONTH | TO_MONTH | MONTHS_IN_RUN | STARTED_AT | ENDED_AT |
|---|---|---|---|---|---|
| 1 | 2023-01-01 | 2023-02-01 | 2 | 5090.50 | 7650.00 |
| 2 | 2023-03-01 | 2023-04-01 | 2 | 7330.75 | 9010.00 |
| 3 | 2023-05-01 | 2023-06-01 | 2 | 3980.25 | 10075.50 |
| 4 | 2023-07-01 | 2023-08-01 | 2 | 7170.00 | 12110.00 |
| 5 | 2023-09-01 | 2023-11-01 | 3 | 5540.00 | 11380.00 |
| 6 | 2023-12-01 | 2024-01-01 | 2 | 8980.00 | 15110.00 |
| 7 | 2024-03-01 | 2024-05-01 | 3 | 2930.00 | 16875.00 |
| 8 | 2024-07-01 | 2024-08-01 | 2 | 8820.00 | 15640.00 |
| 9 | 2024-09-01 | 2024-10-01 | 2 | 7010.00 | 9640.00 |
Still 9 matches. Now look at MONTHS_IN_RUN. Matches 5 and 7 are three months long: September to November 2023, and March to May 2024.
In each of those the series rose twice in succession, so the + absorbed both rises into one match instead of stopping after the first.
The count of matches did not change. The span of two of them did. That is worth noticing, because “9 matches” both times could easily be read as “nothing happened”.
The STARTED_AT and ENDED_AT measures make the climbs concrete. Each one is the total the run began at and the total it ended at.
+, *, ? and {m,n} all work the way they do in a text regular expression, and they are greedy by default — a run takes as many rows as it can rather than stopping at the shortest match. That greed is exactly what turned matches 5 and 7 into three-month runs.
Now let's see the rows inside each match
One row per match is a summary. Let's swap it for ALL ROWS PER MATCH and get the member rows instead.
While we are there we can add CLASSIFIER(), which tells us which symbol each row matched.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
CLASSIFIER() AS SYMBOL
ALL ROWS PER MATCH
PATTERN (A B+)
DEFINE B AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO, MONTH_START;| MONTH_START | TOTAL | MATCH_NO | SYMBOL |
|---|---|---|---|
| 2023-01-01 | 5090.50 | 1 | A |
| 2023-02-01 | 7650.00 | 1 | B |
| 2023-03-01 | 7330.75 | 2 | A |
| 2023-04-01 | 9010.00 | 2 | B |
| 2023-05-01 | 3980.25 | 3 | A |
| 2023-06-01 | 10075.50 | 3 | B |
| 2023-07-01 | 7170.00 | 4 | A |
| 2023-08-01 | 12110.00 | 4 | B |
| 2023-09-01 | 5540.00 | 5 | A |
| 2023-10-01 | 8445.00 | 5 | B |
| 2023-11-01 | 11380.00 | 5 | B |
| 2023-12-01 | 8980.00 | 6 | A |
| 2024-01-01 | 15110.00 | 6 | B |
| 2024-03-01 | 2930.00 | 7 | A |
| 2024-04-01 | 12640.00 | 7 | B |
| 2024-05-01 | 16875.00 | 7 | B |
| 2024-07-01 | 8820.00 | 8 | A |
| 2024-08-01 | 15640.00 | 8 | B |
| 2024-09-01 | 7010.00 | 9 | A |
| 2024-10-01 | 9640.00 | 9 | B |
20 rows, and now the structure is visible. Every match begins with one A and continues with Bs. Match 5 is one A followed by two Bs, which is the three-month climb the B+ query turned up.
Now count the SYMBOL column. There are 9 A rows, one per match, which is what PATTERN (A B+) guarantees. And there are 11 B rows.
11 was the number of UP months we counted with LAG and CASE, and these are the same 11 months. The pattern found every rise in the series and nothing that was not one.
Let's get those three totals in a single row.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT COUNT(*) AS ROWS_IN_ALL_MATCHES,
COUNT(DISTINCT MATCH_NO) AS MATCHES,
(SELECT COUNT(*) FROM M) AS MONTHS_TOTAL
FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO
ALL ROWS PER MATCH
PATTERN (A B+)
DEFINE B AS TOTAL > LAG(TOTAL)
);| ROWS_IN_ALL_MATCHES | MATCHES | MONTHS_TOTAL |
|---|---|---|
| 20 | 9 | 23 |
Three months are in no match at all
20 member rows out of 23 months leaves three months that never appeared. They are worth naming rather than leaving as arithmetic.
Compare the member rows with the series and they are February 2024, June 2024 and November 2024.
- February 2024 and June 2024 are each followed by a month that fell, so neither could start a climb — an
Aneeds at least oneBafter it to complete the pattern. - November 2024 is the last month in the series and its
TOTALisNULL, so it can neither rise nor be risen past.
Which gives us a complete account of the series: 9 months starting a climb, 11 rising, and 3 left out.
Now let's be specific about how many
+ is “one or more”. Braces let us be specific. B{2,} is two or more Bs, which is a climb that lasted at least two months.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(MONTH_START) AS FROM_MONTH,
LAST(MONTH_START) AS TO_MONTH,
COUNT(*) AS MONTHS_IN_RUN
ONE ROW PER MATCH
PATTERN (A B{2,})
DEFINE B AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO;| MATCH_NO | FROM_MONTH | TO_MONTH | MONTHS_IN_RUN |
|---|---|---|---|
| 1 | 2023-09-01 | 2023-11-01 | 3 |
| 2 | 2024-03-01 | 2024-05-01 | 3 |
2 matches, and they are precisely the two three-month runs the B+ query turned up. Nothing new was discovered. The pattern simply refused to report the shorter climbs, which is often what we want from a query like this.
A fixed count, on a symbol that matches anything
A quantifier does not have to sit on a condition. A{3} with A defined as TRUE is “any three consecutive rows”. Let's try it.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(MONTH_START) AS FROM_MONTH,
LAST(MONTH_START) AS TO_MONTH
ONE ROW PER MATCH
PATTERN (A{3})
DEFINE A AS TRUE
)
ORDER BY MATCH_NO;| MATCH_NO | FROM_MONTH | TO_MONTH |
|---|---|---|
| 1 | 2023-01-01 | 2023-03-01 |
| 2 | 2023-04-01 | 2023-06-01 |
| 3 | 2023-07-01 | 2023-09-01 |
| 4 | 2023-10-01 | 2023-12-01 |
| 5 | 2024-01-01 | 2024-03-01 |
| 6 | 2024-04-01 | 2024-06-01 |
| 7 | 2024-07-01 | 2024-09-01 |
7 matches, each three months long and none of them overlapping. The series has been chopped into consecutive threes.
7 matches account for 21 of the 23 months, so two are left over. The last match ends in September 2024, which tells us which two: a partial group is not a match.
DEFINE A AS TRUE looks like noise and is not optional. Snowflake requires a DEFINE clause even when the symbol is meant to match every row, so when a pattern needs an “any row” symbol you give it one and move on. (An undefined symbol also matches anything, as the last step on this page shows, but at least one symbol in the pattern has to be defined.)
Now let's look for a shape: a dip and a recovery
One symbol only gets us so far. Give the pattern two conditions and we can describe a shape rather than a direction.
A month, then one or more falls, then one or more rises. A V.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(MONTH_START) AS FROM_MONTH,
LAST(MONTH_START) AS TO_MONTH,
COUNT(DOWN.*) AS DOWN_MONTHS,
COUNT(UP.*) AS UP_MONTHS
ONE ROW PER MATCH
PATTERN (S DOWN+ UP+)
DEFINE DOWN AS TOTAL < LAG(TOTAL),
UP AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO;| MATCH_NO | FROM_MONTH | TO_MONTH | DOWN_MONTHS | UP_MONTHS |
|---|---|---|---|---|
| 1 | 2023-02-01 | 2023-04-01 | 1 | 1 |
| 2 | 2023-06-01 | 2023-08-01 | 1 | 1 |
| 3 | 2023-11-01 | 2024-01-01 | 1 | 1 |
| 4 | 2024-02-01 | 2024-05-01 | 1 | 2 |
| 5 | 2024-06-01 | 2024-08-01 | 1 | 1 |
5 V-shapes. The two counting measures are the new idea here. COUNT(DOWN.*) counts the rows in this match that matched the symbol DOWN, and COUNT(UP.*) does the same for UP. So we can see the shape of each match without looking at its rows.
Four of the five are one month down and one month up. Match 4 is the exception, with two up months. It fell once and then climbed twice before the pattern ran out of rises.
Let's look at the member rows and see those shapes spelled out.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO, CLASSIFIER() AS SYMBOL
ALL ROWS PER MATCH
PATTERN (S DOWN+ UP+)
DEFINE DOWN AS TOTAL < LAG(TOTAL),
UP AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO, MONTH_START;| MONTH_START | TOTAL | MATCH_NO | SYMBOL |
|---|---|---|---|
| 2023-02-01 | 7650.00 | 1 | S |
| 2023-03-01 | 7330.75 | 1 | DOWN |
| 2023-04-01 | 9010.00 | 1 | UP |
| 2023-06-01 | 10075.50 | 2 | S |
| 2023-07-01 | 7170.00 | 2 | DOWN |
| 2023-08-01 | 12110.00 | 2 | UP |
| 2023-11-01 | 11380.00 | 3 | S |
| 2023-12-01 | 8980.00 | 3 | DOWN |
| 2024-01-01 | 15110.00 | 3 | UP |
| 2024-02-01 | 8340.00 | 4 | S |
| 2024-03-01 | 2930.00 | 4 | DOWN |
| 2024-04-01 | 12640.00 | 4 | UP |
| 2024-05-01 | 16875.00 | 4 | UP |
| 2024-06-01 | 11660.00 | 5 | S |
| 2024-07-01 | 8820.00 | 5 | DOWN |
| 2024-08-01 | 15640.00 | 5 | UP |
16 member rows, and the SYMBOL column spells each shape out: S, DOWN, UP four times over, and S, DOWN, UP, UP for match 4. Five matches of three rows would be fifteen. The extra row is match 4’s second rise.
This is what MATCH_RECOGNIZE is for. “A fall followed by a recovery, of any length, anywhere in the series” is a hard question to ask with window functions. Here it is a one-line pattern.
What does the NULL do?
There is a NULL in this series. November 2024 has no total.
A comparison against NULL is unknown, not true, so a row whose comparison is unknown cannot match a condition. That ought to cost us a match.
The way to find out is to remove the NULL and run the same pattern again. Let's COALESCE the total to zero and change nothing else.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START,
COALESCE(SUM(AMOUNT), 0) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(MONTH_START) AS FROM_MONTH,
LAST(MONTH_START) AS TO_MONTH,
COUNT(*) AS MONTHS_IN_RUN
ONE ROW PER MATCH
PATTERN (A B+)
DEFINE B AS TOTAL > LAG(TOTAL)
)
ORDER BY MATCH_NO;| MATCH_NO | FROM_MONTH | TO_MONTH | MONTHS_IN_RUN |
|---|---|---|---|
| 1 | 2023-01-01 | 2023-02-01 | 2 |
| 2 | 2023-03-01 | 2023-04-01 | 2 |
| 3 | 2023-05-01 | 2023-06-01 | 2 |
| 4 | 2023-07-01 | 2023-08-01 | 2 |
| 5 | 2023-09-01 | 2023-11-01 | 3 |
| 6 | 2023-12-01 | 2024-01-01 | 2 |
| 7 | 2024-03-01 | 2024-05-01 | 3 |
| 8 | 2024-07-01 | 2024-08-01 | 2 |
| 9 | 2024-09-01 | 2024-10-01 | 2 |
9 matches, the same as before. Let's put both counts in one statement so there is no doubt about it.
WITH RAW AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
), ZEROED AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START,
COALESCE(SUM(AMOUNT), 0) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT
(SELECT COUNT(*) FROM RAW MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO
ONE ROW PER MATCH PATTERN (A B+)
DEFINE B AS TOTAL > LAG(TOTAL))) AS MATCHES_WITH_NULL,
(SELECT COUNT(*) FROM ZEROED MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO
ONE ROW PER MATCH PATTERN (A B+)
DEFINE B AS TOTAL > LAG(TOTAL))) AS MATCHES_WITH_ZERO;| MATCHES_WITH_NULL | MATCHES_WITH_ZERO |
|---|---|
| 9 | 9 |
It made no difference, and this post is not going to pretend otherwise.
The reason is specific to where this NULL sits. It is the last month in the series. A final row can only ever end a run, and it ends it either way: as a NULL that cannot match, or as a zero that is lower than the month before it.
The rule still holds even though this data does not demonstrate it: an unknown comparison cannot match, so a NULL in the middle of a series breaks a run in half and you get two shorter matches, or none, where you expected one. Treat gaps in a sequence as something to check for before you pattern-match it — not something to hope about.
Now let's restart the pattern with PARTITION BY
PARTITION BY behaves exactly as it does in every window function from Level 5. The pattern is matched independently inside each group, and a match can never span two groups.
Let's try it on raw orders rather than monthly totals: rising order amounts, per customer.
SELECT * FROM ORDERS
MATCH_RECOGNIZE (
PARTITION BY CUSTOMER_ID
ORDER BY ORDER_DATE, ORDER_ID
MEASURES MATCH_NUMBER() AS MATCH_NO,
FIRST(ORDER_DATE) AS FROM_DATE,
LAST(ORDER_DATE) AS TO_DATE,
COUNT(*) AS ORDERS_IN_RUN,
FIRST(AMOUNT) AS STARTED_AT,
LAST(AMOUNT) AS ENDED_AT
ONE ROW PER MATCH
PATTERN (A B+)
DEFINE B AS AMOUNT > LAG(AMOUNT)
)
ORDER BY CUSTOMER_ID, MATCH_NO;| CUSTOMER_ID | MATCH_NO | FROM_DATE | TO_DATE | ORDERS_IN_RUN | STARTED_AT | ENDED_AT |
|---|---|---|---|---|---|---|
| 101 | 1 | 2023-01-12 | 2023-02-14 | 2 | 4200.00 | 6150.00 |
| 101 | 2 | 2023-03-22 | 2023-06-08 | 2 | 5020.00 | 8100.00 |
| 101 | 3 | 2023-09-16 | 2024-10-16 | 5 | 5540.00 | 9640.00 |
| 102 | 1 | 2023-01-28 | 2023-04-19 | 2 | 890.50 | 1120.00 |
| 102 | 2 | 2023-07-29 | 2024-03-21 | 3 | 750.00 | 1240.00 |
| 103 | 1 | 2023-02-27 | 2023-05-02 | 2 | 1500.00 | 3340.25 |
| 103 | 2 | 2023-08-30 | 2024-05-10 | 3 | 2860.00 | 4025.00 |
| 104 | 1 | 2023-06-25 | 2024-08-02 | 3 | 1975.50 | 2540.00 |
| 105 | 1 | 2023-07-11 | 2024-02-17 | 3 | 6420.00 | 8340.00 |
| 106 | 1 | 2023-05-21 | 2024-03-04 | 3 | 640.00 | 1690.00 |
| 107 | 1 | 2023-08-14 | 2024-08-25 | 5 | 9250.00 | 13100.00 |
| 109 | 1 | 2024-06-30 | 2024-09-11 | 2 | 4760.00 | 5930.00 |
12 runs across 8 customers, and MATCH_NUMBER() restarts inside each one. Customer 101 has three runs numbered 1 to 3, then customer 102 starts again at 1.
Two of the twelve runs are five orders long. The STARTED_AT and ENDED_AT columns show what each climb was worth at both ends.
Note the ORDER BY ORDER_DATE, ORDER_ID inside the clause. A second ordering column is how you make the sequence deterministic when the first one can tie — with ties unresolved, “the previous row” is not a well-defined thing and neither is the pattern built on it.
Can a symbol with no definition match anything?
Earlier we said that A, never defined, matches any row. That is testable, so let's test it.
We take a two-symbol pattern, define only B, and define it as TRUE. Now both symbols match anything.
So every adjacent pair of rows should be a match, none of them overlapping, with one row left over at the end of an odd-length series.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT COUNT(*) AS MATCHES,
(SELECT COUNT(*) FROM M) AS MONTHS
FROM M
MATCH_RECOGNIZE (
ORDER BY MONTH_START
MEASURES MATCH_NUMBER() AS MATCH_NO
ONE ROW PER MATCH
PATTERN (A B)
DEFINE B AS TRUE
);| MATCHES | MONTHS |
|---|---|
| 11 | 23 |
11 matches out of 23 months, which is the prediction exactly. 11 pairs consume 22 months and one month is left without a partner.
An undefined symbol matches every row. That is why the A in every pattern on this page simply took whatever came first.
And the clause that is only optional on paper
The documentation lists ORDER BY as optional inside MATCH_RECOGNIZE, and technically it is. But the moment DEFINE compares a row with the one before it, there has to be an order for “before” to mean anything.
Let's take it out and see.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT * FROM M
MATCH_RECOGNIZE (
MEASURES MATCH_NUMBER() AS MATCH_NO
ONE ROW PER MATCH
PATTERN (A B)
DEFINE B AS TOTAL > LAG(TOTAL)
);002305 (42601): SQL compilation error: error line 10 at position 22 Window frame requires an ORDER BY clause.
Refused, and that is the better outcome by a distance. The alternative would have been a result that ran and quietly meant nothing.
If our pattern depends on sequence, we say what the sequence is.
Key points
MATCH_RECOGNIZEis a regular expression over rows.ORDER BYsays what in sequence means,DEFINEnames the conditions,PATTERNis the expression over those names, andMEASURESis what you get back.- In
DEFINEuseLAG, notPREV.PREV()is allowed only inMEASURES, and the error you get for using it elsewhere names the function, not the rule. ONE ROW PER MATCHgives one summary row per match;ALL ROWS PER MATCHgives the member rows, andCLASSIFIER()names the symbol each row matched.- The quantifiers are the familiar ones and they are greedy:
B+swallowed two consecutive rises into a single three-month run rather than stopping at the first. - A pattern can describe a shape, not just a direction.
PATTERN (S DOWN+ UP+)found every fall-then-recovery in the series, andCOUNT(DOWN.*)reports how many rows matched each symbol. - A symbol with no
DEFINEmatches any row — proved by making both symbols match anything and getting 11 pairs out of 23 rows. At least one symbol must still be defined, andDEFINE A AS TRUEis how you say “any row” explicitly. - Rows can be in no match at all. Here 20 of the 23 months appeared in some match and 3 did not, which is a figure worth checking whenever a pattern looks like it covered everything.
- A comparison against
NULLis unknown, so aNULLrow cannot match a condition. It changed nothing on this data only because theNULLis the last row; in the middle of a series it would break a run in half. PARTITION BYrestarts the pattern in every group and no match spans two groups, exactly as in Level 5.
Episode 63 — MATCH_RECOGNIZE, part 2. AFTER MATCH SKIP and what it does to overlapping matches, MEASURES in depth, and a worked funnel — which closes Level 6.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode, including the error pane. The ORDERS data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series — the argument for MATCH_RECOGNIZE here is that it lets you name the shape you are looking for. Clause behaviour follows the Snowflake MATCH_RECOGNIZE documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.