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
- Let's look at the values we are about to match on
- Let's start with the simple form
- Now let's ship that as a summary
- Let's check whether anything fell through
- Let's fix the comparison three ways and score them
- Now let's run the simple form with the right values
- Now let's try the searched form
- What happens if we write the thresholds the other way round?
- Now let's go back to that Tiny band
- Can the simple form test for NULL?
- Now let's see what ELSE 0 does to an average
- All the branches have to agree on a type
- Now let's put CASE inside SUM for a pivot
- One last thing: CASE inside ORDER BY
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.
-- 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.
SELECT ORDER_ID, CUSTOMER_ID, ORDER_DATE, AMOUNT, STATUS
FROM ORDERS ORDER BY ORDER_ID LIMIT 10;| ORDER_ID | CUSTOMER_ID | ORDER_DATE | AMOUNT | STATUS |
|---|---|---|---|---|
| 1001 | 101 | 2023-01-12 | 4200.00 | SHIPPED |
| 1002 | 102 | 2023-01-28 | 890.50 | SHIPPED |
| 1003 | 101 | 2023-02-14 | 6150.00 | SHIPPED |
| 1004 | 103 | 2023-02-27 | 1500.00 | CANCELLED |
| 1005 | 104 | 2023-03-09 | 2310.75 | SHIPPED |
| 1006 | 101 | 2023-03-22 | 5020.00 | SHIPPED |
| 1007 | 105 | 2023-04-05 | 7890.00 | SHIPPED |
| 1008 | 102 | 2023-04-19 | 1120.00 | SHIPPED |
| 1009 | 103 | 2023-05-02 | 3340.25 | SHIPPED |
| 1010 | 106 | 2023-05-21 | 640.00 | PENDING |
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.
SELECT CUSTOMER_ID, CUSTOMER_NAME, CITY, COUNTRY, SEGMENT
FROM CUSTOMERS ORDER BY CUSTOMER_ID;| CUSTOMER_ID | CUSTOMER_NAME | CITY | COUNTRY | SEGMENT |
|---|---|---|---|---|
| 101 | Northwind Traders | Charlotte | USA | Enterprise |
| 102 | Blue Ridge Supply | Asheville | USA | SMB |
| 103 | Kestrel Analytics | Toronto | Canada | Enterprise |
| 104 | Harbour Foods | Vancouver | Canada | SMB |
| 105 | Alpine Logistics | Zurich | NULL | Enterprise |
| 106 | Delta Print Co | Raleigh | USA | SMB |
| 107 | Meridian Health | Boston | USA | Enterprise |
| 108 | Copper Kettle Ltd | Manchester | UK | SMB |
| 109 | Vantage Media | London | UK | Enterprise |
| 110 | Sable Interiors | Austin | USA | SMB |
One of those countries is NULL. Let's count that properly instead of looking for it by eye.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT(COUNTRY) AS HAVE_A_COUNTRY,
COUNT(*) - COUNT(COUNTRY) AS COUNTRY_IS_NULL
FROM CUSTOMERS;| ROWS_TOTAL | HAVE_A_COUNTRY | COUNTRY_IS_NULL |
|---|---|---|
| 10 | 9 | 1 |
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.
SELECT STATUS, COUNT(*) AS N, ROUND(SUM(AMOUNT), 2) AS TOTAL
FROM ORDERS GROUP BY STATUS ORDER BY N DESC;| STATUS | N | TOTAL |
|---|---|---|
| SHIPPED | 34 | 192307.00 |
| PENDING | 3 | 7540.00 |
| CANCELLED | 2 | 3750.00 |
| RETURNED | 2 | 1830.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.
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;| ORDER_ID | STATUS | PLAIN_ENGLISH |
|---|---|---|
| 1001 | SHIPPED | Unknown |
| 1002 | SHIPPED | Unknown |
| 1003 | SHIPPED | Unknown |
| 1004 | CANCELLED | Unknown |
| 1005 | SHIPPED | Unknown |
| 1006 | SHIPPED | Unknown |
| 1007 | SHIPPED | Unknown |
| 1008 | SHIPPED | Unknown |
| 1009 | SHIPPED | Unknown |
| 1010 | PENDING | Unknown |
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.
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;| PLAIN_ENGLISH | N | TOTAL |
|---|---|---|
| Unknown | 41 | 205427.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.
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.
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;| ROWS_TOTAL | FELL_THROUGH | DISTINCT_STATUSES |
|---|---|---|
| 41 | 41 | 4 |
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.
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;| ROWS_TOTAL | UPPER_BOTH_SIDES | USING_ILIKE | THE_MISTAKE |
|---|---|---|---|
| 41 | 34 | 34 | 0 |
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.
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;| ORDER_ID | STATUS | PLAIN_ENGLISH |
|---|---|---|
| 1001 | SHIPPED | Gone |
| 1002 | SHIPPED | Gone |
| 1003 | SHIPPED | Gone |
| 1004 | CANCELLED | Dead |
| 1005 | SHIPPED | Gone |
| 1006 | SHIPPED | Gone |
| 1007 | SHIPPED | Gone |
| 1008 | SHIPPED | Gone |
| 1009 | SHIPPED | Gone |
| 1010 | PENDING | Waiting |
That works. SHIPPED is Gone and CANCELLED is Dead. Let's summarise it the same way we did before.
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;| PLAIN_ENGLISH | N | TOTAL |
|---|---|---|
| Gone | 34 | 192307.00 |
| Waiting | 3 | 7540.00 |
| Unknown | 2 | 1830.00 |
| Dead | 2 | 3750.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.
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;| ROWS_TOTAL | FELL_THROUGH | DISTINCT_STATUSES |
|---|---|---|
| 41 | 2 | 4 |
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.
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.
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;| ORDER_ID | AMOUNT | BAND |
|---|---|---|
| 1041 | NULL | Tiny |
| 1037 | 13100.00 | Large |
| 1032 | 12850.00 | Large |
| 1025 | 11200.00 | Large |
| 1020 | 10400.00 | Large |
| 1040 | 9640.00 | Large |
| 1015 | 9250.00 | Large |
| 1035 | 8820.00 | Large |
| 1026 | 8340.00 | Large |
| 1011 | 8100.00 | Large |
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.
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;| BAND | N | SMALLEST | LARGEST |
|---|---|---|---|
| Medium | 4 | 640.00 | 980.00 |
| Large | 36 | 1080.00 | 13100.00 |
| Tiny | 1 | NULL | NULL |
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.
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;| BAND | N | SMALLEST | LARGEST |
|---|---|---|---|
| Small | 40 | 640.00 | 13100.00 |
| Tiny | 1 | NULL | NULL |
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.
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;| ORDER_ID | AMOUNT | DESCENDING_ORDER | ASCENDING_ORDER |
|---|---|---|---|
| 1041 | NULL | Tiny | Tiny |
| 1037 | 13100.00 | Large | Small |
| 1032 | 12850.00 | Large | Small |
| 1025 | 11200.00 | Large | Small |
| 1020 | 10400.00 | Large | Small |
| 1040 | 9640.00 | Large | Small |
| 1015 | 9250.00 | Large | Small |
| 1035 | 8820.00 | Large | Small |
| 1026 | 8340.00 | Large | Small |
| 1011 | 8100.00 | Large | Small |
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.
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;| ROWS_TOTAL | CLASSIFIED_DIFFERENTLY |
|---|---|
| 41 | 40 |
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.
| ORDER_ID | AMOUNT | BAND |
|---|---|---|
| 1041 | NULL | Tiny |
| 1037 | 13100.00 | Large |
| 1032 | 12850.00 | Large |
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.
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;| ORDER_ID | AMOUNT | NO_ELSE | WITH_ELSE |
|---|---|---|---|
| 1010 | 640.00 | Medium | Medium |
| 1014 | 750.00 | Medium | Medium |
| 1002 | 890.50 | Medium | Medium |
| 1021 | 980.00 | Medium | Medium |
| 1039 | 1080.00 | Large | Large |
| 1008 | 1120.00 | Large | Large |
| 1028 | 1240.00 | Large | Large |
| 1018 | 1430.00 | Large | Large |
| 1004 | 1500.00 | Large | Large |
| 1027 | 1690.00 | Large | Large |
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.
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;| ROWS_TOTAL | MATCHED | BECAME_NULL |
|---|---|---|
| 41 | 40 | 1 |
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.
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;| BAND | N | TOTAL |
|---|---|---|
| Large | 36 | 202166.50 |
| Medium | 4 | 3260.50 |
| NULL | 1 | NULL |
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.
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.
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;| CUSTOMER_ID | CUSTOMER_NAME | COUNTRY | SIMPLE_FORM | SEARCHED_FORM |
|---|---|---|---|---|
| 101 | Northwind Traders | USA | Domestic | Domestic |
| 102 | Blue Ridge Supply | USA | Domestic | Domestic |
| 103 | Kestrel Analytics | Canada | International | International |
| 104 | Harbour Foods | Canada | International | International |
| 105 | Alpine Logistics | NULL | International | Missing |
| 106 | Delta Print Co | USA | Domestic | Domestic |
| 107 | Meridian Health | USA | Domestic | Domestic |
| 108 | Copper Kettle Ltd | UK | International | International |
| 109 | Vantage Media | UK | International | International |
| 110 | Sable Interiors | USA | Domestic | Domestic |
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.
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;| ROWS_TOTAL | SIMPLE_FORM_FOUND | SEARCHED_FORM_FOUND | ACTUAL_NULLS |
|---|---|---|---|
| 10 | 0 | 1 | 1 |
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.
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;| NULL_EQUALS_NULL | NULL_IS_NULL | NULL_NOT_EQUALS_NULL | THE_COMPARISON_ITSELF_IS_NULL | EQUAL_NULL_FUNCTION |
|---|---|---|---|---|
| NULL | TRUE | NULL | NULL | TRUE |
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.
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;| AVG_NO_ELSE | AVG_ELSE_ZERO | ROWS_IN_FIRST | ROWS_IN_SECOND |
|---|---|---|---|
| NULL | 0.00 | 0 | 41 |
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.
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;| AVG_NO_ELSE | AVG_ELSE_ZERO | ROWS_IN_FIRST | ROWS_IN_SECOND |
|---|---|---|---|
| 5656.09 | 4690.41 | 34 | 41 |
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.
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;| BOTH_NUMBERS | NUMBER_AND_TEXT | ITS_TYPE | NUMBER_AND_NULL |
|---|---|---|---|
| 1 | 1 | INTEGER | 1 |
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.
SELECT CASE WHEN AMOUNT >= 1000 THEN AMOUNT ELSE 'small' END AS SHOULD_NOT_GET_THIS_FAR
FROM ORDERS;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.
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;| ORDER_ID | AMOUNT | AS_TEXT | AS_NUMBER |
|---|---|---|---|
| 1041 | NULL | small | 0.00 |
| 1037 | 13100.00 | 13100.00 | 13100.00 |
| 1032 | 12850.00 | 12850.00 | 12850.00 |
| 1025 | 11200.00 | 11200.00 | 11200.00 |
| 1020 | 10400.00 | 10400.00 | 10400.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.
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;| COUNTRY | ORDERS_ | SHIPPED | PENDING | CANCELLED | SHIPPED_VALUE |
|---|---|---|---|---|---|
| USA | 24 | 0 | 0 | 0 | 0.00 |
| Canada | 9 | 0 | 0 | 0 | 0.00 |
| NULL | 5 | 0 | 0 | 0 | 0.00 |
| UK | 3 | 0 | 0 | 0 | 0.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?
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;| ORDERS_TOTAL | THE_THREE_ADDED_UP | UNACCOUNTED_FOR |
|---|---|---|
| 41 | 0 | 41 |
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.
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;| COUNTRY | ORDERS_ | SHIPPED | PENDING | CANCELLED | RETURNED | SHIPPED_VALUE |
|---|---|---|---|---|---|---|
| USA | 24 | 20 | 2 | 0 | 2 | 125810.50 |
| Canada | 9 | 7 | 0 | 2 | 0 | 20961.50 |
| NULL | 5 | 4 | 1 | 0 | 0 | 29665.00 |
| UK | 3 | 3 | 0 | 0 | 0 | 15870.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.
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;| ORDERS_TOTAL | THE_FOUR_ADDED_UP | UNACCOUNTED_FOR |
|---|---|---|
| 41 | 41 | 0 |
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.
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;| ORDER_ID | STATUS | AMOUNT |
|---|---|---|
| 1041 | PENDING | NULL |
| 1037 | SHIPPED | 13100.00 |
| 1032 | SHIPPED | 12850.00 |
| 1025 | SHIPPED | 11200.00 |
| 1020 | SHIPPED | 10400.00 |
| 1040 | SHIPPED | 9640.00 |
| 1015 | SHIPPED | 9250.00 |
| 1035 | SHIPPED | 8820.00 |
| 1026 | SHIPPED | 8340.00 |
| 1011 | SHIPPED | 8100.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.
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;| ORDER_ID | STATUS | AMOUNT |
|---|---|---|
| 1033 | PENDING | 6900.00 |
| 1010 | PENDING | 640.00 |
| 1041 | PENDING | NULL |
| 1037 | SHIPPED | 13100.00 |
| 1032 | SHIPPED | 12850.00 |
| 1025 | SHIPPED | 11200.00 |
| 1020 | SHIPPED | 10400.00 |
| 1040 | SHIPPED | 9640.00 |
| 1015 | SHIPPED | 9250.00 |
| 1035 | SHIPPED | 8820.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.
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;| ORDER_ID | STATUS | AMOUNT | SIMPLE_FORM | SEARCHED_FORM | NULL_SAFE |
|---|---|---|---|---|---|
| 1001 | SHIPPED | 4200.00 | Other | Large | Present |
| 1002 | SHIPPED | 890.50 | Other | Medium | Present |
| 1003 | SHIPPED | 6150.00 | Other | Large | Present |
| 1004 | CANCELLED | 1500.00 | Other | Large | Present |
| 1005 | SHIPPED | 2310.75 | Other | Large | Present |
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
CASEhas two forms. The simple form compares one column to a list of values. The searched form takes a full condition in everyWHEN, 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
WHENbranches againstCOUNT(DISTINCT column). That catches the category you forgot, which a value check never will. CASEstops at the firstWHENthat is true, so overlapping thresholds have to be written tightest first.- A
GROUP BYdoes not show you an empty group, so a band yourCASEnever produced is absent rather than zero. NULLmatches noWHEN, so a missing value lands in whatever yourELSEsays — which is how a missing amount gets reported as the smallest band.WHEN NULLin the simple form compiles and never fires, because it means= NULL. Use the searched form withIS NULLin its own branch.- Leave out the
ELSEand non-matching rows becomeNULL, which forms its own visible group in aGROUP BY. ELSE 0changes an average, because zero is a value andNULLis 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.
CASEinsideSUMgives you a conditional pivot. Always check that the columns add up to the total.CASEinsideORDER BYgives a custom sort order — and a broken one can still put the right row on top by accident.
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.