Snowflake SQL Tutorial 62 - MATCH_RECOGNIZE in Snowflake

Snowflake SQL · Episode 62

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

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.

Sample data — run once, then build M
-- 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.

Query — the input to everything that follows
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;
Result23 rows · 3 columns
MONTH_STARTN_ORDERSTOTAL
2023-01-0125090.50
2023-02-0127650.00
2023-03-0127330.75
2023-04-0129010.00
2023-05-0123980.25
2023-06-01210075.50
2023-07-0127170.00
2023-08-01212110.00
2023-09-0115540.00
2023-10-0128445.00
2023-11-01211380.00
2023-12-0128980.00
2024-01-01215110.00
2024-02-0118340.00
2024-03-0122930.00
2024-04-01212640.00
2024-05-01216875.00
2024-06-01211660.00
2024-07-0118820.00
2024-08-01215640.00
2024-09-0127010.00
2024-10-0119640.00
2024-11-011NULL

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.

Query — LAG and CASE
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;
Result23 rows · 4 columns
MONTH_STARTTOTALPREV_TOTALDIRECTION
2023-01-015090.50NULLNULL
2023-02-017650.005090.50UP
2023-03-017330.757650.00DOWN
2023-04-019010.007330.75UP
2023-05-013980.259010.00DOWN
2023-06-0110075.503980.25UP
2023-07-017170.0010075.50DOWN
2023-08-0112110.007170.00UP
2023-09-015540.0012110.00DOWN
2023-10-018445.005540.00UP
2023-11-0111380.008445.00UP
2023-12-018980.0011380.00DOWN
2024-01-0115110.008980.00UP
2024-02-018340.0015110.00DOWN
2024-03-012930.008340.00DOWN
2024-04-0112640.002930.00UP
2024-05-0116875.0012640.00UP
2024-06-0111660.0016875.00DOWN
2024-07-018820.0011660.00DOWN
2024-08-0115640.008820.00UP
2024-09-017010.0015640.00DOWN
2024-10-019640.007010.00UP
2024-11-01NULL9640.00NULL

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.

Query — the same column, counted
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;
Result1 row · 4 columns
MONTHSUP_MONTHSDOWN_MONTHSUNDECIDED
2311102

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_TOTAL to compare against.
  • November 2024 — the final month, whose own TOTAL is NULL, 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.

Query
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;
Result9 rows · 4 columns
MATCH_NOFROM_MONTHTO_MONTHROWS_IN_MATCH
12023-01-012023-02-012
22023-03-012023-04-012
32023-05-012023-06-012
42023-07-012023-08-012
52023-09-012023-10-012
62023-12-012024-01-012
72024-03-012024-04-012
82024-07-012024-08-012
92024-09-012024-10-012
  1. ORDER BY — what in sequence means. Everything else is defined relative to this order.
  2. MEASURES — what you get back about each match. MATCH_NUMBER() numbers the matches, and FIRST, LAST and COUNT read across the rows the match contains.
  3. ONE ROW PER MATCH — the shape of the output: one summary row per match rather than the member rows.
  4. PATTERN — the regular expression, written over symbol names rather than characters.
  5. 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.

The rule that costs people an afternoon

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 grammar rules

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.

Query — PATTERN (A B+)
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;
Result9 rows · 6 columns · scroll →
MATCH_NOFROM_MONTHTO_MONTHMONTHS_IN_RUNSTARTED_ATENDED_AT
12023-01-012023-02-0125090.507650.00
22023-03-012023-04-0127330.759010.00
32023-05-012023-06-0123980.2510075.50
42023-07-012023-08-0127170.0012110.00
52023-09-012023-11-0135540.0011380.00
62023-12-012024-01-0128980.0015110.00
72024-03-012024-05-0132930.0016875.00
82024-07-012024-08-0128820.0015640.00
92024-09-012024-10-0127010.009640.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.

The quantifiers are the familiar ones

+, *, ? 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.

Query — ALL ROWS PER MATCH with CLASSIFIER()
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;
Result20 rows · 4 columns
MONTH_STARTTOTALMATCH_NOSYMBOL
2023-01-015090.501A
2023-02-017650.001B
2023-03-017330.752A
2023-04-019010.002B
2023-05-013980.253A
2023-06-0110075.503B
2023-07-017170.004A
2023-08-0112110.004B
2023-09-015540.005A
2023-10-018445.005B
2023-11-0111380.005B
2023-12-018980.006A
2024-01-0115110.006B
2024-03-012930.007A
2024-04-0112640.007B
2024-05-0116875.007B
2024-07-018820.008A
2024-08-0115640.008B
2024-09-017010.009A
2024-10-019640.009B

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.

Query — the three totals in one 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)
);
Result1 row · 3 columns
ROWS_IN_ALL_MATCHESMATCHESMONTHS_TOTAL
20923

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 A needs at least one B after it to complete the pattern.
  • November 2024 is the last month in the series and its TOTAL is NULL, 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.

Query — PATTERN (A B{2,})
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;
Result2 rows · 4 columns
MATCH_NOFROM_MONTHTO_MONTHMONTHS_IN_RUN
12023-09-012023-11-013
22024-03-012024-05-013

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.

Query — PATTERN (A{3})
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;
Result7 rows · 3 columns
MATCH_NOFROM_MONTHTO_MONTH
12023-01-012023-03-01
22023-04-012023-06-01
32023-07-012023-09-01
42023-10-012023-12-01
52024-01-012024-03-01
62024-04-012024-06-01
72024-07-012024-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.

Why DEFINE A AS TRUE is there

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.

Query — PATTERN (S DOWN+ UP+)
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;
Result5 rows · 5 columns
MATCH_NOFROM_MONTHTO_MONTHDOWN_MONTHSUP_MONTHS
12023-02-012023-04-0111
22023-06-012023-08-0111
32023-11-012024-01-0111
42024-02-012024-05-0112
52024-06-012024-08-0111

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.

Query — the same pattern, ALL ROWS PER MATCH
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;
Result16 rows · 4 columns
MONTH_STARTTOTALMATCH_NOSYMBOL
2023-02-017650.001S
2023-03-017330.751DOWN
2023-04-019010.001UP
2023-06-0110075.502S
2023-07-017170.002DOWN
2023-08-0112110.002UP
2023-11-0111380.003S
2023-12-018980.003DOWN
2024-01-0115110.003UP
2024-02-018340.004S
2024-03-012930.004DOWN
2024-04-0112640.004UP
2024-05-0116875.004UP
2024-06-0111660.005S
2024-07-018820.005DOWN
2024-08-0115640.005UP

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.

Query — the same pattern with the NULL coalesced to 0
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;
Result9 rows · 4 columns
MATCH_NOFROM_MONTHTO_MONTHMONTHS_IN_RUN
12023-01-012023-02-012
22023-03-012023-04-012
32023-05-012023-06-012
42023-07-012023-08-012
52023-09-012023-11-013
62023-12-012024-01-012
72024-03-012024-05-013
82024-07-012024-08-012
92024-09-012024-10-012

9 matches, the same as before. Let's put both counts in one statement so there is no doubt about it.

Query — with the NULL, and with a zero
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;
Result1 row · 2 columns
MATCHES_WITH_NULLMATCHES_WITH_ZERO
99

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.

What this grid does not prove

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.

Query — PARTITION BY CUSTOMER_ID
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;
Result12 rows · 7 columns · scroll →
CUSTOMER_IDMATCH_NOFROM_DATETO_DATEORDERS_IN_RUNSTARTED_ATENDED_AT
10112023-01-122023-02-1424200.006150.00
10122023-03-222023-06-0825020.008100.00
10132023-09-162024-10-1655540.009640.00
10212023-01-282023-04-192890.501120.00
10222023-07-292024-03-213750.001240.00
10312023-02-272023-05-0221500.003340.25
10322023-08-302024-05-1032860.004025.00
10412023-06-252024-08-0231975.502540.00
10512023-07-112024-02-1736420.008340.00
10612023-05-212024-03-043640.001690.00
10712023-08-142024-08-2559250.0013100.00
10912024-06-302024-09-1124760.005930.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.

Why the order has two columns

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.

Query — PATTERN (A B) with nothing that can fail
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
);
Result1 row · 2 columns
MATCHESMONTHS
1123

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.

Query — no ORDER BY
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)
);
Query failed — Snowflake returned an error
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_RECOGNIZE is a regular expression over rows. ORDER BY says what in sequence means, DEFINE names the conditions, PATTERN is the expression over those names, and MEASURES is what you get back.
  • In DEFINE use LAG, not PREV. PREV() is allowed only in MEASURES, and the error you get for using it elsewhere names the function, not the rule.
  • ONE ROW PER MATCH gives one summary row per match; ALL ROWS PER MATCH gives the member rows, and CLASSIFIER() 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, and COUNT(DOWN.*) reports how many rows matched each symbol.
  • A symbol with no DEFINE matches 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, and DEFINE A AS TRUE is 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 NULL is unknown, so a NULL row cannot match a condition. It changed nothing on this data only because the NULL is the last row; in the middle of a series it would break a run in half.
  • PARTITION BY restarts the pattern in every group and no match spans two groups, exactly as in Level 5.
Next in this series

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.