Snowflake SQL Tutorial 79 - CASE WHEN, Simple vs Searched, NULL - The ELSE Trap

Snowflake SQL · Episode 79

In this post we are going to cover CASE in Snowflake.

CASE is how you put an IF statement inside a query. You give it a list of conditions and a value for each one, and it hands back the value belonging to the first condition that is true. It comes in two forms, and they are not interchangeable.

We will start with the simple form and build it up step by step. On the way we will write a status report that comes back with one single row on it, put a thirteen thousand one hundred dollar order in a band called Small, and find out that a CASE which is wrong still returns rows and still shows no error.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 79 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

This post runs against the ORDERS and CUSTOMERS tables that the rest of the course uses. The script below just points the worksheet at them.

Copy it into a Snowflake worksheet and run it once.

Sample data
-- ORDERS and CUSTOMERS come from the setup script this course uses
-- throughout. Run it once; every episode reuses the same tables.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

Here are the first ten orders, so we can see what we are working with.

Query
SELECT ORDER_ID, CUSTOMER_ID, ORDER_DATE, AMOUNT, STATUS
FROM ORDERS ORDER BY ORDER_ID LIMIT 10;
Result10 rows · 5 columns
ORDER_IDCUSTOMER_IDORDER_DATEAMOUNTSTATUS
10011012023-01-124200.00SHIPPED
10021022023-01-28890.50SHIPPED
10031012023-02-146150.00SHIPPED
10041032023-02-271500.00CANCELLED
10051042023-03-092310.75SHIPPED
10061012023-03-225020.00SHIPPED
10071052023-04-057890.00SHIPPED
10081022023-04-191120.00SHIPPED
10091032023-05-023340.25SHIPPED
10101062023-05-21640.00PENDING

An order ID, a customer ID, a date, an amount and a status. The whole table has more rows than this, and we will put the real count on screen in a moment rather than guess at it.

We will need the customers as well, because the second half of this post is about a missing country.

Query
SELECT CUSTOMER_ID, CUSTOMER_NAME, CITY, COUNTRY, SEGMENT
FROM CUSTOMERS ORDER BY CUSTOMER_ID;
Result10 rows · 5 columns
CUSTOMER_IDCUSTOMER_NAMECITYCOUNTRYSEGMENT
101Northwind TradersCharlotteUSAEnterprise
102Blue Ridge SupplyAshevilleUSASMB
103Kestrel AnalyticsTorontoCanadaEnterprise
104Harbour FoodsVancouverCanadaSMB
105Alpine LogisticsZurichNULLEnterprise
106Delta Print CoRaleighUSASMB
107Meridian HealthBostonUSAEnterprise
108Copper Kettle LtdManchesterUKSMB
109Vantage MediaLondonUKEnterprise
110Sable InteriorsAustinUSASMB

One of those countries is NULL. Let's count that properly instead of looking for it by eye.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(COUNTRY) AS HAVE_A_COUNTRY,
       COUNT(*) - COUNT(COUNTRY) AS COUNTRY_IS_NULL
FROM CUSTOMERS;
Result1 row · 3 columns
ROWS_TOTALHAVE_A_COUNTRYCOUNTRY_IS_NULL
1091

Ten customers, nine of them with a country, one without. Hold on to that one.

Let's look at the values we are about to match on

The simple form of CASE compares one column against a list of values, so before we write it, let's see what is actually in the column.

Query
SELECT STATUS, COUNT(*) AS N, ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS GROUP BY STATUS ORDER BY N DESC;
Result4 rows · 3 columns
STATUSNTOTAL
SHIPPED34192307.00
PENDING37540.00
CANCELLED23750.00
RETURNED21830.00

Four statuses. SHIPPED has 34 orders, PENDING has 3, CANCELLED has 2 and RETURNED has 2. Those add up to 41, which is the whole table.

Now look at how they are written. All capitals. Keep that in mind, because it is about to matter more than it looks.

Let's start with the simple form

The simple form is CASE, then the column, then a WHEN for each value we want to match, then ELSE for everything we did not list.

Let's turn the status into something a person would read.

Query
SELECT ORDER_ID, STATUS,
       CASE STATUS
            WHEN 'Shipped'   THEN 'Gone'
            WHEN 'Pending'   THEN 'Waiting'
            WHEN 'Cancelled' THEN 'Dead'
            ELSE 'Unknown'
       END AS PLAIN_ENGLISH
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 10;
Result10 rows · 3 columns
ORDER_IDSTATUSPLAIN_ENGLISH
1001SHIPPEDUnknown
1002SHIPPEDUnknown
1003SHIPPEDUnknown
1004CANCELLEDUnknown
1005SHIPPEDUnknown
1006SHIPPEDUnknown
1007SHIPPEDUnknown
1008SHIPPEDUnknown
1009SHIPPEDUnknown
1010PENDINGUnknown

Every row says Unknown. All ten of them — the SHIPPED rows, the CANCELLED one and the PENDING one alike.

The reason is in the query, not in the data. We wrote 'Shipped' with a capital S and the rest in lower case. The table says SHIPPED. String comparison in Snowflake is case sensitive, so no WHEN matched anything, and every row went to the ELSE.

There is no error. The query is valid. It just answers a question nobody asked.

Now let's ship that as a summary

Nobody reads a row-by-row grid in production. They read a summary. So let's group that same CASE and count it, which is how this would actually go out.

Query
SELECT CASE STATUS
            WHEN 'Shipped'   THEN 'Gone'
            WHEN 'Pending'   THEN 'Waiting'
            WHEN 'Cancelled' THEN 'Dead'
            ELSE 'Unknown'
       END AS PLAIN_ENGLISH,
       COUNT(*) AS N, ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS
GROUP BY 1
ORDER BY N DESC;
Result1 row · 3 columns
PLAIN_ENGLISHNTOTAL
Unknown41205427.00

One row. Unknown, 41 orders, 205427.00 of value.

That is a status report with a single line on it. It is arithmetically correct and completely useless, and nothing on the screen says so.

The thing to take away

This is the shape of the whole episode. A CASE that is wrong does not fail. It returns rows, it returns totals that add up, and it puts a confident label on all of them.

Let's check whether anything fell through

That summary had nothing to compare itself against. So let's write the check: how many rows are there, how many landed in the ELSE, and how many distinct statuses exist.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(CASE STATUS
                     WHEN 'Shipped'   THEN 'Gone'
                     WHEN 'Pending'   THEN 'Waiting'
                     WHEN 'Cancelled' THEN 'Dead'
                     ELSE 'Unknown'
                END = 'Unknown') AS FELL_THROUGH,
       COUNT(DISTINCT STATUS) AS DISTINCT_STATUSES
FROM ORDERS;
Result1 row · 3 columns
ROWS_TOTALFELL_THROUGHDISTINCT_STATUSES
41414

41 rows in the table, 41 of them fell through, and there are 4 distinct statuses the query should have been able to name.

That is the query worth writing. One line, and it would have caught this before the report went anywhere.

Let's fix the comparison three ways and score them

Before we rewrite the CASE, let's find out what each way of comparing actually scores on this data. UPPER on both sides, ILIKE, and the mistake we just made, side by side.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(UPPER(STATUS) = 'SHIPPED')                       AS UPPER_BOTH_SIDES,
       COUNT_IF(STATUS ILIKE 'shipped')                          AS USING_ILIKE,
       COUNT_IF(STATUS = 'Shipped')                              AS THE_MISTAKE
FROM ORDERS;
Result1 row · 4 columns
ROWS_TOTALUPPER_BOTH_SIDESUSING_ILIKETHE_MISTAKE
4134340

UPPER(STATUS) = 'SHIPPED' finds 34 rows. STATUS ILIKE 'shipped' also finds 34. STATUS = 'Shipped' finds none at all.

So either put UPPER on both sides, or use ILIKE, which ignores case for you. What you cannot do is trust your own typing.

Now let's run the simple form with the right values

Easiest of all, since we now know what the column holds, is to write the values the way the data writes them.

Query
SELECT ORDER_ID, STATUS,
       CASE STATUS
            WHEN 'SHIPPED'   THEN 'Gone'
            WHEN 'PENDING'   THEN 'Waiting'
            WHEN 'CANCELLED' THEN 'Dead'
            ELSE 'Unknown'
       END AS PLAIN_ENGLISH
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 10;
Result10 rows · 3 columns
ORDER_IDSTATUSPLAIN_ENGLISH
1001SHIPPEDGone
1002SHIPPEDGone
1003SHIPPEDGone
1004CANCELLEDDead
1005SHIPPEDGone
1006SHIPPEDGone
1007SHIPPEDGone
1008SHIPPEDGone
1009SHIPPEDGone
1010PENDINGWaiting

That works. SHIPPED is Gone and CANCELLED is Dead. Let's summarise it the same way we did before.

Query
SELECT CASE STATUS
            WHEN 'SHIPPED'   THEN 'Gone'
            WHEN 'PENDING'   THEN 'Waiting'
            WHEN 'CANCELLED' THEN 'Dead'
            ELSE 'Unknown'
       END AS PLAIN_ENGLISH,
       COUNT(*) AS N, ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS
GROUP BY 1
ORDER BY N DESC;
Result4 rows · 3 columns
PLAIN_ENGLISHNTOTAL
Gone34192307.00
Waiting37540.00
Unknown21830.00
Dead23750.00

Four rows now instead of one. Gone 34, Waiting 3, Unknown 2 and Dead 2.

And that Unknown row is the second bug, sitting directly beside Dead and looking exactly like a category of its own. Let's run the same check again.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(CASE STATUS
                     WHEN 'SHIPPED'   THEN 'Gone'
                     WHEN 'PENDING'   THEN 'Waiting'
                     WHEN 'CANCELLED' THEN 'Dead'
                     ELSE 'Unknown'
                END = 'Unknown') AS FELL_THROUGH,
       COUNT(DISTINCT STATUS) AS DISTINCT_STATUSES
FROM ORDERS;
Result1 row · 3 columns
ROWS_TOTALFELL_THROUGHDISTINCT_STATUSES
4124

2 rows still fall through, and there are still 4 distinct statuses. We wrote three WHEN branches for four statuses, so RETURNED has no branch and those 2 orders land in the ELSE.

Have a look at the TOTAL on that Unknown row in the grid above: 1830.00. That is the same number as the RETURNED row of our very first summary. The category did not disappear. It got renamed to Unknown.

The check

Count your WHEN branches against COUNT(DISTINCT column). That is the check worth writing, and it is the one that catches a category you forgot rather than a value you mistyped.

Now let's try the searched form

The searched form drops the column after CASE. Every WHEN then takes a full condition instead of just a value, so you can test ranges, combinations, anything.

Let's put the orders into amount bands. A thousand or more is Large, five hundred or more is Medium, a hundred or more is Small, anything else is Tiny.

Query
SELECT ORDER_ID, AMOUNT,
       CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
            WHEN AMOUNT >= 100  THEN 'Small'
            ELSE 'Tiny'
       END AS BAND
FROM ORDERS
ORDER BY AMOUNT DESC
LIMIT 10;
Result10 rows · 3 columns
ORDER_IDAMOUNTBAND
1041NULLTiny
103713100.00Large
103212850.00Large
102511200.00Large
102010400.00Large
10409640.00Large
10159250.00Large
10358820.00Large
10268340.00Large
10118100.00Large

That reads correctly, and the big amounts are all Large. Let's turn it into a summary so we can see every band at once, with the smallest and largest amount in each.

Query
SELECT CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
            WHEN AMOUNT >= 100  THEN 'Small'
            ELSE 'Tiny'
       END AS BAND,
       COUNT(*) AS N, MIN(AMOUNT) AS SMALLEST, MAX(AMOUNT) AS LARGEST
FROM ORDERS
GROUP BY 1
ORDER BY SMALLEST;
Result3 rows · 4 columns
BANDNSMALLESTLARGEST
Medium4640.00980.00
Large361080.0013100.00
Tiny1NULLNULL

Medium has 4 orders running from 640.00 to 980.00, and Large has 36. Those plus the single Tiny order make 41.

But look at that Tiny row. Its smallest and largest amounts are both NULL. We will come back to it.

What happens if we write the thresholds the other way round?

Same three thresholds, same data, same bands. The only thing we are going to change is the order the WHEN branches are written in: a hundred first, then five hundred, then a thousand.

Query
SELECT CASE WHEN AMOUNT >= 100  THEN 'Small'
            WHEN AMOUNT >= 500  THEN 'Medium'
            WHEN AMOUNT >= 1000 THEN 'Large'
            ELSE 'Tiny'
       END AS BAND,
       COUNT(*) AS N, MIN(AMOUNT) AS SMALLEST, MAX(AMOUNT) AS LARGEST
FROM ORDERS
GROUP BY 1
ORDER BY SMALLEST;
Result2 rows · 4 columns
BANDNSMALLESTLARGEST
Small40640.0013100.00
Tiny1NULLNULL

Small has 40 orders, and its largest is 13100.00.

A thirteen thousand one hundred dollar order, in a band called Small.

And look at what else happened. Medium and Large are not on the report. Not zero. Gone. A GROUP BY does not show you an empty group, so nothing on that screen tells you that two of your four categories were never produced.

Let's put both orderings on the same rows, side by side, so there is no arguing with it.

Query
SELECT ORDER_ID, AMOUNT,
       CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
            WHEN AMOUNT >= 100  THEN 'Small'
            ELSE 'Tiny' END AS DESCENDING_ORDER,
       CASE WHEN AMOUNT >= 100  THEN 'Small'
            WHEN AMOUNT >= 500  THEN 'Medium'
            WHEN AMOUNT >= 1000 THEN 'Large'
            ELSE 'Tiny' END AS ASCENDING_ORDER
FROM ORDERS
ORDER BY AMOUNT DESC
LIMIT 10;
Result10 rows · 4 columns
ORDER_IDAMOUNTDESCENDING_ORDERASCENDING_ORDER
1041NULLTinyTiny
103713100.00LargeSmall
103212850.00LargeSmall
102511200.00LargeSmall
102010400.00LargeSmall
10409640.00LargeSmall
10159250.00LargeSmall
10358820.00LargeSmall
10268340.00LargeSmall
10118100.00LargeSmall

Same order ID, same amount, Large in one column and Small in the other. And let's count how far that spreads across the table.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(CASE WHEN AMOUNT >= 1000 THEN 'Large'
                     WHEN AMOUNT >= 500  THEN 'Medium'
                     WHEN AMOUNT >= 100  THEN 'Small'
                     ELSE 'Tiny' END
                <> CASE WHEN AMOUNT >= 100  THEN 'Small'
                        WHEN AMOUNT >= 500  THEN 'Medium'
                        WHEN AMOUNT >= 1000 THEN 'Large'
                        ELSE 'Tiny' END) AS CLASSIFIED_DIFFERENTLY
FROM ORDERS;
Result1 row · 2 columns
ROWS_TOTALCLASSIFIED_DIFFERENTLY
4140

40 of the 41 rows are classified differently by the two orderings.

The reason is one sentence. CASE stops at the first WHEN that is true. 13100.00 is more than a hundred, so the first branch matched, and nothing after it was ever considered.

So order your conditions tightest first, or write them so they cannot overlap at all.

Now let's go back to that Tiny band

The Tiny band had one order in it and both its amounts were NULL. Look at the top row of the searched-form grid again: order 1041 has no amount at all, and it has been labelled Tiny.

Result10 rows · 3 columns · showing first 3
The first three rows again, sorted by amount descending
ORDER_IDAMOUNTBAND
1041NULLTiny
103713100.00Large
103212850.00Large

NULL >= 1000 is not false. It is NULL. NULL is not true, so no WHEN matched, and the row fell through to the ELSE.

A missing amount has been reported as the smallest band. That is not a technicality, it is a reporting bug.

So let's take the ELSE away entirely and see what those rows become instead.

Query
SELECT ORDER_ID, AMOUNT,
       CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
       END AS NO_ELSE,
       CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
            ELSE 'Everything else'
       END AS WITH_ELSE
FROM ORDERS
ORDER BY AMOUNT
LIMIT 10;
Result10 rows · 4 columns
ORDER_IDAMOUNTNO_ELSEWITH_ELSE
1010640.00MediumMedium
1014750.00MediumMedium
1002890.50MediumMedium
1021980.00MediumMedium
10391080.00LargeLarge
10081120.00LargeLarge
10281240.00LargeLarge
10181430.00LargeLarge
10041500.00LargeLarge
10271690.00LargeLarge

Those two columns agree on every row in this grid, and that is worth explaining rather than skipping. The grid is sorted by amount ascending, the smallest amount in the table is 640.00, and the one row where the two columns differ is the row with no amount — which an ascending sort puts at the very bottom, out of sight.

So let's count it instead of looking for it.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(CASE WHEN AMOUNT >= 1000 THEN 'Large'
                  WHEN AMOUNT >= 500  THEN 'Medium' END) AS MATCHED,
       COUNT(*) - COUNT(CASE WHEN AMOUNT >= 1000 THEN 'Large'
                             WHEN AMOUNT >= 500  THEN 'Medium' END) AS BECAME_NULL
FROM ORDERS;
Result1 row · 3 columns
ROWS_TOTALMATCHEDBECAME_NULL
41401

41 rows, 40 of them matched a branch, and 1 became NULL. Not zero, not Tiny, not 'Everything else'. NULL.

Now let's see what a GROUP BY does with that.

Query
SELECT CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
       END AS BAND,
       COUNT(*) AS N, ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS
GROUP BY 1
ORDER BY N DESC;
Result3 rows · 3 columns
BANDNTOTAL
Large36202166.50
Medium43260.50
NULL1NULL

Three rows: Large, Medium, and a band of NULL holding 1 order. The row that matched nothing did not disappear. It formed a group of its own, which is the one thing in this whole post that was visible without being counted.

Which of the two is better

An ELSE that quietly relabels a missing value is worse than no ELSE at all. Tiny looks like an answer. A NULL group at the bottom of a report looks like a question, and that is what you want it to look like.

Can the simple form test for NULL?

That is the obvious next thought. The simple form takes a list of values, and NULL looks like a value, so let's write WHEN NULL THEN 'Missing' and put the searched form next to it for comparison.

Query
SELECT CUSTOMER_ID, CUSTOMER_NAME, COUNTRY,
       CASE COUNTRY
            WHEN 'USA'  THEN 'Domestic'
            WHEN NULL   THEN 'Missing'
            ELSE 'International'
       END AS SIMPLE_FORM,
       CASE WHEN COUNTRY IS NULL THEN 'Missing'
            WHEN COUNTRY = 'USA' THEN 'Domestic'
            ELSE 'International'
       END AS SEARCHED_FORM
FROM CUSTOMERS
ORDER BY CUSTOMER_ID;
Result10 rows · 5 columns
CUSTOMER_IDCUSTOMER_NAMECOUNTRYSIMPLE_FORMSEARCHED_FORM
101Northwind TradersUSADomesticDomestic
102Blue Ridge SupplyUSADomesticDomestic
103Kestrel AnalyticsCanadaInternationalInternational
104Harbour FoodsCanadaInternationalInternational
105Alpine LogisticsNULLInternationalMissing
106Delta Print CoUSADomesticDomestic
107Meridian HealthUSADomesticDomestic
108Copper Kettle LtdUKInternationalInternational
109Vantage MediaUKInternationalInternational
110Sable InteriorsUSADomesticDomestic

It compiles and it runs. Now find customer 105, Alpine Logistics, whose country is NULL. The simple form calls it International. The searched form, on the same row, calls it Missing.

Let's count what each form found.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(CASE COUNTRY WHEN 'USA' THEN 'Domestic' WHEN NULL THEN 'Missing'
                             ELSE 'International' END = 'Missing') AS SIMPLE_FORM_FOUND,
       COUNT_IF(CASE WHEN COUNTRY IS NULL THEN 'Missing'
                     WHEN COUNTRY = 'USA' THEN 'Domestic'
                     ELSE 'International' END = 'Missing')         AS SEARCHED_FORM_FOUND,
       COUNT(*) - COUNT(COUNTRY) AS ACTUAL_NULLS
FROM CUSTOMERS;
Result1 row · 4 columns
ROWS_TOTALSIMPLE_FORM_FOUNDSEARCHED_FORM_FOUNDACTUAL_NULLS
10011

The simple form found 0 nulls. The searched form found 1. And the actual number of nulls in the column is 1.

The reason is that WHEN NULL in the simple form is a comparison. It means COUNTRY = NULL, and that is never true. Let's look at the comparison on its own.

Query
SELECT NULL = NULL        AS NULL_EQUALS_NULL,
       NULL IS NULL       AS NULL_IS_NULL,
       NULL <> NULL       AS NULL_NOT_EQUALS_NULL,
       NULL = NULL IS NULL AS THE_COMPARISON_ITSELF_IS_NULL,
       EQUAL_NULL(NULL, NULL) AS EQUAL_NULL_FUNCTION;
Result1 row · 5 columns
NULL_EQUALS_NULLNULL_IS_NULLNULL_NOT_EQUALS_NULLTHE_COMPARISON_ITSELF_IS_NULLEQUAL_NULL_FUNCTION
NULLTRUENULLNULLTRUE

NULL = NULL is NULL. NULL IS NULL is TRUE. NULL <> NULL is NULL as well. And EQUAL_NULL(NULL, NULL) is TRUE, because that function is the null-safe comparison.

So the simple form cannot test for NULL at all. If a column can be NULL and you care about it, use the searched form and give IS NULL its own branch.

Now let's see what ELSE 0 does to an average

The common advice is to always write an ELSE, usually ELSE 0. Let's find out what that actually does, by averaging a CASE with and without it.

And this is the same mistyped status from the beginning of the post, on purpose, because it is worth seeing what this bug looks like inside an aggregate.

Query
SELECT ROUND(AVG(CASE WHEN STATUS = 'Shipped' THEN AMOUNT END), 2)         AS AVG_NO_ELSE,
       ROUND(AVG(CASE WHEN STATUS = 'Shipped' THEN AMOUNT ELSE 0 END), 2)  AS AVG_ELSE_ZERO,
       COUNT(CASE WHEN STATUS = 'Shipped' THEN AMOUNT END)                 AS ROWS_IN_FIRST,
       COUNT(CASE WHEN STATUS = 'Shipped' THEN AMOUNT ELSE 0 END)          AS ROWS_IN_SECOND
FROM ORDERS;
Result1 row · 4 columns
AVG_NO_ELSEAVG_ELSE_ZEROROWS_IN_FIRSTROWS_IN_SECOND
NULL0.00041

The average with no ELSE is NULL. The average with ELSE 0 is 0.00. And the row counts explain both: 0 rows went into the first one, 41 into the second.

Nothing matched, so there was nothing to average. That is what that looks like — and it is loud. An average of NULL over zero rows is hard to miss, which is the opposite of the tidy one-line report we got earlier from exactly the same mistake.

Now let's spell the status correctly and run it again.

Query
SELECT ROUND(AVG(CASE WHEN STATUS = 'SHIPPED' THEN AMOUNT END), 2)        AS AVG_NO_ELSE,
       ROUND(AVG(CASE WHEN STATUS = 'SHIPPED' THEN AMOUNT ELSE 0 END), 2) AS AVG_ELSE_ZERO,
       COUNT(CASE WHEN STATUS = 'SHIPPED' THEN AMOUNT END)                AS ROWS_IN_FIRST,
       COUNT(CASE WHEN STATUS = 'SHIPPED' THEN AMOUNT ELSE 0 END)         AS ROWS_IN_SECOND
FROM ORDERS;
Result1 row · 4 columns
AVG_NO_ELSEAVG_ELSE_ZEROROWS_IN_FIRSTROWS_IN_SECOND
5656.094690.413441

Without the ELSE, the average is 5656.09 over 34 rows. With ELSE 0, it is 4690.41 over 41 rows.

Those 7 extra rows are the ones that did not match. ELSE 0 turned each of them into a zero, and an average has to carry every zero you give it.

Zero is a value. NULL is not. That is the whole difference, and it is a decision about what the number means, not a tidy-up.

All the branches have to agree on a type

A CASE returns one column, so every branch has to produce the same type. Snowflake will convert for you where it can. Let's see where it can.

Query
SELECT CASE WHEN TRUE THEN 1 ELSE 2 END          AS BOTH_NUMBERS,
       CASE WHEN TRUE THEN 1 ELSE '2' END        AS NUMBER_AND_TEXT,
       TYPEOF((CASE WHEN TRUE THEN 1 ELSE '2' END)::VARIANT) AS ITS_TYPE,
       CASE WHEN TRUE THEN 1 ELSE NULL END       AS NUMBER_AND_NULL;
Result1 row · 4 columns
BOTH_NUMBERSNUMBER_AND_TEXTITS_TYPENUMBER_AND_NULL
11INTEGER1

WHEN TRUE THEN 1 ELSE '2' returns 1, and TYPEOF says INTEGER. The text '2' was coerced to a number quietly, because it could be.

Now let's give it a word that is not a number.

Query
SELECT CASE WHEN AMOUNT >= 1000 THEN AMOUNT ELSE 'small' END AS SHOULD_NOT_GET_THIS_FAR
FROM ORDERS;
Query failed — Snowflake returned an error
100038 (22018): Numeric value 'small' is not recognized

Numeric value 'small' is not recognized. Snowflake decided the column was numeric, because the first branch returns AMOUNT, and then tried to make 'small' into a number.

The fix is to cast, so that the branches agree on purpose rather than by luck. Either make both text, or make both numbers.

Query
SELECT ORDER_ID, AMOUNT,
       CASE WHEN AMOUNT >= 1000 THEN AMOUNT::VARCHAR ELSE 'small' END AS AS_TEXT,
       CASE WHEN AMOUNT >= 1000 THEN AMOUNT ELSE 0 END                AS AS_NUMBER
FROM ORDERS
ORDER BY AMOUNT DESC
LIMIT 5;
Result5 rows · 4 columns
ORDER_IDAMOUNTAS_TEXTAS_NUMBER
1041NULLsmall0.00
103713100.0013100.0013100.00
103212850.0012850.0012850.00
102511200.0011200.0011200.00
102010400.0010400.0010400.00

Both columns work now. AS_TEXT gives the word small for the row with no amount, and AS_NUMBER gives 0.00 for the same row. Two different answers, both deliberate.

Now let's put CASE inside SUM for a pivot

Here is where CASE earns its keep. Put it inside SUM, with 1 in the matching branch and 0 in the ELSE, and you get one column per category. That is a conditional pivot.

Let's count orders by country, with a column per status.

Query
SELECT C.COUNTRY,
       COUNT(*) AS ORDERS_,
       SUM(CASE WHEN O.STATUS = 'Shipped'   THEN 1 ELSE 0 END) AS SHIPPED,
       SUM(CASE WHEN O.STATUS = 'Pending'   THEN 1 ELSE 0 END) AS PENDING,
       SUM(CASE WHEN O.STATUS = 'Cancelled' THEN 1 ELSE 0 END) AS CANCELLED,
       ROUND(SUM(CASE WHEN O.STATUS = 'Shipped' THEN O.AMOUNT ELSE 0 END), 2) AS SHIPPED_VALUE
FROM ORDERS O
JOIN CUSTOMERS C ON C.CUSTOMER_ID = O.CUSTOMER_ID
GROUP BY C.COUNTRY
ORDER BY ORDERS_ DESC;
Result4 rows · 6 columns · scroll →
COUNTRYORDERS_SHIPPEDPENDINGCANCELLEDSHIPPED_VALUE
USA240000.00
Canada90000.00
NULL50000.00
UK30000.00

The country side of that is right. The USA has 24 orders, Canada has 9, the customer with no country has 5 and the UK has 3, and those add up to 41.

Everything else on that grid is zero. Every status column, on every row, and the shipped value too — because this is the capital-S 'Shipped' mistake again, now hiding inside an aggregate where there is nothing to compare it to.

There is a check that catches this, and it is the check that makes any pivot trustworthy: do the columns add up to the total?

Query
SELECT COUNT(*) AS ORDERS_TOTAL,
       SUM(CASE WHEN STATUS = 'Shipped'   THEN 1 ELSE 0 END)
       + SUM(CASE WHEN STATUS = 'Pending' THEN 1 ELSE 0 END)
       + SUM(CASE WHEN STATUS = 'Cancelled' THEN 1 ELSE 0 END) AS THE_THREE_ADDED_UP,
       COUNT(*) - (SUM(CASE WHEN STATUS = 'Shipped'   THEN 1 ELSE 0 END)
                 + SUM(CASE WHEN STATUS = 'Pending'   THEN 1 ELSE 0 END)
                 + SUM(CASE WHEN STATUS = 'Cancelled' THEN 1 ELSE 0 END)) AS UNACCOUNTED_FOR
FROM ORDERS;
Result1 row · 3 columns
ORDERS_TOTALTHE_THREE_ADDED_UPUNACCOUNTED_FOR
41041

41 orders in total, the three status columns add to 0, and 41 orders are unaccounted for. That is the check doing exactly its job.

So let's fix the spelling and add the RETURNED column we were missing.

Query
SELECT C.COUNTRY,
       COUNT(*) AS ORDERS_,
       SUM(CASE WHEN O.STATUS = 'SHIPPED'   THEN 1 ELSE 0 END) AS SHIPPED,
       SUM(CASE WHEN O.STATUS = 'PENDING'   THEN 1 ELSE 0 END) AS PENDING,
       SUM(CASE WHEN O.STATUS = 'CANCELLED' THEN 1 ELSE 0 END) AS CANCELLED,
       SUM(CASE WHEN O.STATUS = 'RETURNED'  THEN 1 ELSE 0 END) AS RETURNED,
       ROUND(SUM(CASE WHEN O.STATUS = 'SHIPPED' THEN O.AMOUNT ELSE 0 END), 2)
         AS SHIPPED_VALUE
FROM ORDERS O
JOIN CUSTOMERS C ON C.CUSTOMER_ID = O.CUSTOMER_ID
GROUP BY C.COUNTRY
ORDER BY ORDERS_ DESC;
Result4 rows · 7 columns · scroll →
COUNTRYORDERS_SHIPPEDPENDINGCANCELLEDRETURNEDSHIPPED_VALUE
USA2420202125810.50
Canada9702020961.50
NULL5410029665.00
UK3300015870.00

Now it reads. The USA has 20 shipped, 2 pending, none cancelled and 2 returned, and those four add across to its 24 orders. Every row adds across the same way, and down the columns the four totals are 34, 3, 2 and 2, which is the status grid we started the post with.

And the check, one more time.

Query
SELECT COUNT(*) AS ORDERS_TOTAL,
       SUM(CASE WHEN STATUS = 'SHIPPED'   THEN 1 ELSE 0 END)
       + SUM(CASE WHEN STATUS = 'PENDING' THEN 1 ELSE 0 END)
       + SUM(CASE WHEN STATUS = 'CANCELLED' THEN 1 ELSE 0 END)
       + SUM(CASE WHEN STATUS = 'RETURNED'  THEN 1 ELSE 0 END) AS THE_FOUR_ADDED_UP,
       COUNT(*) - (SUM(CASE WHEN STATUS = 'SHIPPED'   THEN 1 ELSE 0 END)
                 + SUM(CASE WHEN STATUS = 'PENDING'   THEN 1 ELSE 0 END)
                 + SUM(CASE WHEN STATUS = 'CANCELLED' THEN 1 ELSE 0 END)
                 + SUM(CASE WHEN STATUS = 'RETURNED'  THEN 1 ELSE 0 END))
         AS UNACCOUNTED_FOR
FROM ORDERS;
Result1 row · 3 columns
ORDERS_TOTALTHE_FOUR_ADDED_UPUNACCOUNTED_FOR
41410

41 orders, the four columns add to 41, nothing unaccounted for. If that last number is not zero, you are missing a column.

One last thing: CASE inside ORDER BY

The other place CASE turns up is in ORDER BY, for a sort order that is not alphabetical and not numeric. Pending first, then shipped, then cancelled, then everything else.

And this is the broken spelling one final time, because of what it looks like when it runs.

Query
SELECT ORDER_ID, STATUS, AMOUNT
FROM ORDERS
ORDER BY CASE STATUS WHEN 'Pending' THEN 1
                     WHEN 'Shipped' THEN 2
                     WHEN 'Cancelled' THEN 3
                     ELSE 4 END,
         AMOUNT DESC
LIMIT 10;
Result10 rows · 3 columns
ORDER_IDSTATUSAMOUNT
1041PENDINGNULL
1037SHIPPED13100.00
1032SHIPPED12850.00
1025SHIPPED11200.00
1020SHIPPED10400.00
1040SHIPPED9640.00
1015SHIPPED9250.00
1035SHIPPED8820.00
1026SHIPPED8340.00
1011SHIPPED8100.00

The top row is PENDING. So it looks like it worked.

It did not. Every single row got ELSE 4, so the CASE sorted nothing at all and the tiebreak did all the work. AMOUNT DESC puts the row with no amount first in Snowflake, and that row happens to be PENDING.

The proof is what is missing. There are 3 pending orders in this table, and the other two are nowhere in these ten rows.

Let's fix the values and put the nulls last on the tiebreak.

Query
SELECT ORDER_ID, STATUS, AMOUNT
FROM ORDERS
ORDER BY CASE STATUS WHEN 'PENDING'   THEN 1
                     WHEN 'SHIPPED'   THEN 2
                     WHEN 'CANCELLED' THEN 3
                     ELSE 4 END,
         AMOUNT DESC NULLS LAST
LIMIT 10;
Result10 rows · 3 columns
ORDER_IDSTATUSAMOUNT
1033PENDING6900.00
1010PENDING640.00
1041PENDINGNULL
1037SHIPPED13100.00
1032SHIPPED12850.00
1025SHIPPED11200.00
1020SHIPPED10400.00
1040SHIPPED9640.00
1015SHIPPED9250.00
1035SHIPPED8820.00

All 3 pending orders are at the top now: 6900.00, then 640.00, then the one with no amount. The shipped orders follow.

That is the lesson of the whole post in one grid. A CASE that is wrong still returns rows, and sometimes it returns rows that look right.

Here is everything on a few rows together, so you can see the two forms and a null-safe test side by side.

Query
SELECT ORDER_ID, STATUS, AMOUNT,
       CASE STATUS WHEN 'Shipped' THEN 'Gone' WHEN 'Pending' THEN 'Waiting'
                   ELSE 'Other' END AS SIMPLE_FORM,
       CASE WHEN AMOUNT >= 1000 THEN 'Large'
            WHEN AMOUNT >= 500  THEN 'Medium'
            ELSE 'Small' END        AS SEARCHED_FORM,
       CASE WHEN AMOUNT IS NULL THEN 'Missing' ELSE 'Present' END AS NULL_SAFE
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 5;
Result5 rows · 6 columns · scroll →
ORDER_IDSTATUSAMOUNTSIMPLE_FORMSEARCHED_FORMNULL_SAFE
1001SHIPPED4200.00OtherLargePresent
1002SHIPPED890.50OtherMediumPresent
1003SHIPPED6150.00OtherLargePresent
1004CANCELLED1500.00OtherLargePresent
1005SHIPPED2310.75OtherLargePresent

The simple form says Other for every one of them, because it is matching 'Shipped' against SHIPPED once more. The searched form bands the amounts. And NULL_SAFE asks the only question the simple form cannot ask.

Key points

  • CASE has two forms. The simple form compares one column to a list of values. The searched form takes a full condition in every WHEN, and it is the one to reach for.
  • String comparison is case sensitive. A mistyped value matches nothing, every row goes to the ELSE, and there is no error anywhere.
  • Count your WHEN branches against COUNT(DISTINCT column). That catches the category you forgot, which a value check never will.
  • CASE stops at the first WHEN that is true, so overlapping thresholds have to be written tightest first.
  • A GROUP BY does not show you an empty group, so a band your CASE never produced is absent rather than zero.
  • NULL matches no WHEN, so a missing value lands in whatever your ELSE says — which is how a missing amount gets reported as the smallest band.
  • WHEN NULL in the simple form compiles and never fires, because it means = NULL. Use the searched form with IS NULL in its own branch.
  • Leave out the ELSE and non-matching rows become NULL, which forms its own visible group in a GROUP BY.
  • ELSE 0 changes an average, because zero is a value and NULL is not. That is a decision about meaning, not tidying up.
  • All branches must agree on a type. Snowflake coerces where it can and errors where it cannot, so cast on purpose.
  • CASE inside SUM gives you a conditional pivot. Always check that the columns add up to the total.
  • CASE inside ORDER BY gives a custom sort order — and a broken one can still put the right row on top by accident.
Next in this series

Episode 80 — the null handling family. IFF, NVL, NVL2, COALESCE, NULLIF and DECODE, including the one of them that can match a NULL where the simple CASE form cannot.

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. The ORDERS and CUSTOMERS data is invented demo data created by that script. Where the narration and a grid disagreed, the grid was followed: the first conditional pivot on this page has three status columns and not four, every one of them reads zero, and its own add-up check reports all 41 orders unaccounted for. No performance or benchmark claims are made anywhere in this series. Clause behaviour follows the Snowflake CASE documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.