Snowflake SQL Tutorial 81 - ZEROIFNULL, NULLIFZERO, GREATEST, LEAST, EQUAL_NULL

Snowflake SQL · Episode 81

In this post we are going to cover ZEROIFNULL, NULLIFZERO, GREATEST, LEAST and the null-safe comparisons in Snowflake.

The first two are short names for things you already know. GREATEST and LEAST pick the biggest or smallest from a list of values on one row. And EQUAL_NULL and IS DISTINCT FROM are a way of comparing that treats NULL as a value, which ordinary = does not.

We will start with the two shorthands and build it up step by step. On the way we will write a guaranteed minimum bonus that pays nothing to five people, apply the obvious fix and watch it ruin a cap, and find a column that does not equal itself.

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

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

Let's create some sample data

This post runs against the same EMPLOYEES table as the rest of the course. The script below just points the worksheet at it.

Copy it into a Snowflake worksheet and run it once.

Sample data
-- EMPLOYEES 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;
Query
SELECT EMP_ID, FIRST_NAME, LAST_NAME, DEPT_ID, MANAGER_ID, SALARY,
       COMMISSION_PCT, HIRE_DATE
FROM EMPLOYEES ORDER BY EMP_ID;
Result8 rows · 8 columns · scroll →
EMP_IDFIRST_NAMELAST_NAMEDEPT_IDMANAGER_IDSALARYCOMMISSION_PCTHIRE_DATE
1AishaKhan106118000.00NULL2019-03-11
2MarcusReid10696500.00NULL2021-07-01
3LenaFischer206104000.000.052018-01-22
4TomasNovak20387250.00NULL2022-09-05
5PriyaRaman30696500.000.102020-11-17
6DanielO'Connor10NULL131000.00NULL2016-05-30
7SofiaMarino30571400.000.082023-02-13
8GraceLinNULL692000.00NULL2021-04-19

The column that matters here is COMMISSION_PCT. Let's count what is in it.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(COMMISSION_PCT) AS HAVE_A_RATE,
       COUNT(*) - COUNT(COMMISSION_PCT) AS RATE_IS_NULL,
       COUNT(MANAGER_ID) AS HAVE_A_MANAGER,
       COUNT(*) - COUNT(MANAGER_ID) AS MANAGER_IS_NULL
FROM EMPLOYEES;
Result1 row · 5 columns
ROWS_TOTALHAVE_A_RATERATE_IS_NULLHAVE_A_MANAGERMANAGER_IS_NULL
83571

8 rows. 3 have a commission rate and 5 do not. 7 have a manager and 1 does not.

Those 5 missing rates are the whole subject of this post.

Let's start with ZEROIFNULL

ZEROIFNULL takes one argument. If it is NULL you get zero, and otherwise you get the value. So it is NVL(x, 0) with a shorter name.

Let's put the two side by side and compare them on every row.

Query
SELECT EMP_ID, COMMISSION_PCT,
       ZEROIFNULL(COMMISSION_PCT)   AS ZEROIFNULL_,
       NVL(COMMISSION_PCT, 0)       AS NVL_FOR_COMPARISON,
       ZEROIFNULL(COMMISSION_PCT) = NVL(COMMISSION_PCT, 0) AS SAME
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 5 columns
EMP_IDCOMMISSION_PCTZEROIFNULL_NVL_FOR_COMPARISONSAME
1NULL0.000.00TRUE
2NULL0.000.00TRUE
30.050.050.05TRUE
4NULL0.000.00TRUE
50.100.100.10TRUE
6NULL0.000.00TRUE
70.080.080.08TRUE
8NULL0.000.00TRUE

The SAME column is TRUE all the way down. There is no difference in behaviour at all, just in how much you type.

When the replacement really is zero, the shorter name reads better. When it is anything else, you need NVL anyway.

Now NULLIFZERO, which goes the other way

NULLIFZERO turns a zero into a NULL. That is NULLIF(x, 0) with a shorter name.

Let's run it on the rate after a ZEROIFNULL, so there are some zeros for it to find, with a plain NULLIF beside it and two literal examples on the end.

Query
SELECT EMP_ID, COMMISSION_PCT,
       NULLIFZERO(ZEROIFNULL(COMMISSION_PCT))     AS NULLIFZERO_,
       NULLIF(ZEROIFNULL(COMMISSION_PCT), 0)      AS NULLIF_FOR_COMPARISON,
       NULLIFZERO(0)                              AS ZERO_BECOMES_NULL,
       NULLIFZERO(5)                              AS NON_ZERO_SURVIVES
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 6 columns · scroll →
EMP_IDCOMMISSION_PCTNULLIFZERO_NULLIF_FOR_COMPARISONZERO_BECOMES_NULLNON_ZERO_SURVIVES
1NULLNULLNULLNULL5
2NULLNULLNULLNULL5
30.050.050.05NULL5
4NULLNULLNULLNULL5
50.100.100.10NULL5
6NULLNULLNULLNULL5
70.080.080.08NULL5
8NULLNULLNULLNULL5

NULLIFZERO(0) is NULL and NULLIFZERO(5) is 5. And the two middle columns match each other on every row.

Let's count both agreements in one query rather than reading them off.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(ZEROIFNULL(COMMISSION_PCT) = NVL(COMMISSION_PCT, 0))
         AS ZEROIFNULL_AGREES,
       COUNT_IF(EQUAL_NULL(NULLIFZERO(ZEROIFNULL(COMMISSION_PCT)),
                           NULLIF(ZEROIFNULL(COMMISSION_PCT), 0)))
         AS NULLIFZERO_AGREES
FROM EMPLOYEES;
Result1 row · 3 columns
ROWS_TOTALZEROIFNULL_AGREESNULLIFZERO_AGREES
888

8 rows, and both shorthands agree with their longer form on all 8.

Can we go there and back again?

Those two functions are inverses, so the obvious question is whether a round trip gets you back what you started with. ZEROIFNULL, then NULLIFZERO, then compare against the original.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(EQUAL_NULL(NULLIFZERO(ZEROIFNULL(COMMISSION_PCT)), COMMISSION_PCT))
         AS SURVIVED_THE_ROUND_TRIP,
       COUNT_IF(COMMISSION_PCT = 0) AS GENUINE_ZEROS_THAT_WOULD_BECOME_NULL
FROM EMPLOYEES;
Result1 row · 3 columns
ROWS_TOTALSURVIVED_THE_ROUND_TRIPGENUINE_ZEROS_THAT_WOULD_BECOME_NULL
880

8 of 8 rows came back to what they were.

But the third column is the one to read. It counts the genuine zeros in the column, and there are none.

That is the only reason the round trip was safe. If somebody had a real commission rate of zero, NULLIFZERO would turn it into a NULL and the round trip would quietly lose it. A real zero and a missing value are not the same thing.

The check to run first

Before you trust a NULLIFZERO anywhere, count the genuine zeros in the column. If the answer is not zero, the function is destroying data rather than tidying it.

Now let's look at GREATEST and LEAST

Give them a list of values and they give you back the biggest or the smallest one. Let's try numbers, text and dates.

Query
SELECT GREATEST(1, 5, 3)         AS GREATEST_NUMBERS,
       LEAST(1, 5, 3)            AS LEAST_NUMBERS,
       GREATEST('a', 'c', 'b')   AS GREATEST_TEXT,
       LEAST(DATE '2024-01-01', DATE '2024-06-30') AS LEAST_DATE;
Result1 row · 4 columns
GREATEST_NUMBERSLEAST_NUMBERSGREATEST_TEXTLEAST_DATE
51c2024-01-01

GREATEST(1, 5, 3) is 5 and LEAST(1, 5, 3) is 1. On text it sorts alphabetically, and on dates it compares as dates.

These work across columns, not down them

This is the thing people get wrong, so it is worth a grid of its own. GREATEST looks across the arguments on one row. It is not an aggregate.

Let's put the salary and the commission beside each other, take the greater of the two, and then put MAX(SALARY) OVER () next to it for comparison.

Query
SELECT EMP_ID, SALARY, ROUND(SALARY * ZEROIFNULL(COMMISSION_PCT), 2) AS COMMISSION,
       GREATEST(SALARY, SALARY * ZEROIFNULL(COMMISSION_PCT)) AS BIGGER_OF_THE_TWO,
       MAX(SALARY) OVER ()                                   AS MAX_SALARY_ACROSS_ROWS
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 5 columns
EMP_IDSALARYCOMMISSIONBIGGER_OF_THE_TWOMAX_SALARY_ACROSS_ROWS
1118000.000.00118000.0000131000.00
296500.000.0096500.0000131000.00
3104000.005200.00104000.0000131000.00
487250.000.0087250.0000131000.00
596500.009650.0096500.0000131000.00
6131000.000.00131000.0000131000.00
771400.005712.0071400.0000131000.00
892000.000.0092000.0000131000.00

BIGGER_OF_THE_TWO is worked out separately on each row. Here the salary wins every time, so that column follows the salary down the grid.

MAX_SALARY_ACROSS_ROWS is 131000.00 on every row, because it is one answer for the whole table.

Two completely different questions. GREATEST goes across, MAX goes down.

A quick note on types, and this one is sharp

Comparison depends on type, so GREATEST depends on type. Let's ask for the greatest of the text '10' and the text '9', and then the same thing as numbers.

Query
SELECT GREATEST(1, '5')           AS NUMBER_AND_TEXT,
       TYPEOF(GREATEST(1, '5')::VARIANT) AS ITS_TYPE,
       GREATEST('10', '9')        AS BOTH_TEXT,
       GREATEST(10, 9)            AS BOTH_NUMBERS;
Result1 row · 4 columns
NUMBER_AND_TEXTITS_TYPEBOTH_TEXTBOTH_NUMBERS
5INTEGER910

As text the answer is 9, because text sorts character by character and 9 comes after 1. As numbers the answer is 10. Same values, different type, different answer.

This is the same trap as the conversion post in Episode 77. Mixing a number and text picks a type and converts, and TYPEOF here says INTEGER.

What does one null do to GREATEST?

The name quietly suggests ignore the null and take the biggest of the rest. Let's find out.

Query
SELECT GREATEST(1, 5, NULL)      AS GREATEST_WITH_NULL,
       LEAST(1, 5, NULL)         AS LEAST_WITH_NULL,
       GREATEST(NULL, NULL)      AS ALL_NULL,
       GREATEST(1, 5)            AS NO_NULL_FOR_COMPARISON;
Result1 row · 4 columns
GREATEST_WITH_NULLLEAST_WITH_NULLALL_NULLNO_NULL_FOR_COMPARISON
NULLNULLNULL5

GREATEST(1, 5, NULL) is NULL. LEAST(1, 5, NULL) is NULL as well. Not 5, not 1. The last column shows the same call without the null, and that one returns 5.

Any null argument makes the whole thing NULL. Remember that for the next section, because the next section is what it costs.

Now let's write a guaranteed minimum bonus

Here is something somebody would really write. Everyone gets their commission, or five thousand, whichever is bigger. GREATEST(SALARY * COMMISSION_PCT, 5000).

That reads correctly. Let's run it.

Query
SELECT EMP_ID, FIRST_NAME, SALARY, COMMISSION_PCT,
       ROUND(SALARY * COMMISSION_PCT, 2)              AS COMMISSION,
       GREATEST(SALARY * COMMISSION_PCT, 5000)        AS BONUS
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 6 columns · scroll →
EMP_IDFIRST_NAMESALARYCOMMISSION_PCTCOMMISSIONBONUS
1Aisha118000.00NULLNULLNULL
2Marcus96500.00NULLNULLNULL
3Lena104000.000.055200.005200.0000
4Tomas87250.00NULLNULLNULL
5Priya96500.000.109650.009650.0000
6Daniel131000.00NULLNULLNULL
7Sofia71400.000.085712.005712.0000
8Grace92000.00NULLNULLNULL

Lena gets 5200.0000, Priya gets 9650.0000 and Sofia gets 5712.0000. Everybody else gets NULL.

Not five thousand. NULL. The guarantee did not fire, because their commission is NULL and GREATEST with any null argument is NULL.

Let's put the number up.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(GREATEST(SALARY * COMMISSION_PCT, 5000))            AS GOT_A_BONUS,
       COUNT(*) - COUNT(GREATEST(SALARY * COMMISSION_PCT, 5000)) AS GOT_NULL,
       COUNT(*) - COUNT(COMMISSION_PCT)                          AS ROWS_WITH_NO_RATE
FROM EMPLOYEES;
Result1 row · 4 columns
ROWS_TOTALGOT_A_BONUSGOT_NULLROWS_WITH_NO_RATE
8355

8 rows. 3 got a bonus. 5 got NULL. And 5 rows have no commission rate.

Those are the same 5 rows, and it is not a coincidence. The minimum bonus paid nothing to exactly the people who had no commission — which is to say, the people a floor was for.

Let's fix it with ZEROIFNULL

The fix is to wrap the commission in ZEROIFNULL inside the GREATEST, so there is no null argument left for it to trip over.

Let's run both versions side by side.

Query
SELECT EMP_ID, SALARY, COMMISSION_PCT,
       GREATEST(SALARY * COMMISSION_PCT, 5000)             AS NULL_MEANS_UNKNOWN,
       GREATEST(SALARY * ZEROIFNULL(COMMISSION_PCT), 5000) AS NULL_MEANS_NO_COMMISSION
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 5 columns
EMP_IDSALARYCOMMISSION_PCTNULL_MEANS_UNKNOWNNULL_MEANS_NO_COMMISSION
1118000.00NULLNULL5000.0000
296500.00NULLNULL5000.0000
3104000.000.055200.00005200.0000
487250.00NULLNULL5000.0000
596500.000.109650.00009650.0000
6131000.00NULLNULL5000.0000
771400.000.085712.00005712.0000
892000.00NULLNULL5000.0000

The last column pays 5000.0000 to every row that had no rate, and leaves the three real commissions alone. The floor applies now.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(GREATEST(SALARY * ZEROIFNULL(COMMISSION_PCT), 5000)) AS GOT_A_BONUS,
       MIN(GREATEST(SALARY * ZEROIFNULL(COMMISSION_PCT), 5000))   AS SMALLEST_BONUS,
       COUNT_IF(GREATEST(SALARY * ZEROIFNULL(COMMISSION_PCT), 5000) = 5000)
         AS ON_THE_FLOOR
FROM EMPLOYEES;
Result1 row · 4 columns
ROWS_TOTALGOT_A_BONUSSMALLEST_BONUSON_THE_FLOOR
885000.00005

8 rows, 8 got a bonus, the smallest is 5000.0000, and 5 of them are sitting exactly on the floor. Which is what a floor is for.

But notice what we just did. We decided that a missing rate means no commission. Look at the two column names in the grid above: NULL_MEANS_UNKNOWN and NULL_MEANS_NO_COMMISSION. That is the real difference between them.

It might be right. It might also be that the rate simply has not been entered yet. The function cannot know, so you decided — and it is worth deciding on purpose.

Now let's apply the identical fix to a cap

Same situation, other direction. This time it is a cap: your commission, or eight thousand, whichever is smaller. And we will make exactly the same edit, wrapping the rate in ZEROIFNULL.

Query
SELECT EMP_ID, SALARY, COMMISSION_PCT,
       LEAST(SALARY * COMMISSION_PCT, 8000)             AS NULL_MEANS_UNKNOWN,
       LEAST(SALARY * ZEROIFNULL(COMMISSION_PCT), 8000) AS NULL_MEANS_ZERO
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 5 columns
EMP_IDSALARYCOMMISSION_PCTNULL_MEANS_UNKNOWNNULL_MEANS_ZERO
1118000.00NULLNULL0.0000
296500.00NULLNULL0.0000
3104000.000.055200.00005200.0000
487250.00NULLNULL0.0000
596500.000.108000.00008000.0000
6131000.00NULLNULL0.0000
771400.000.085712.00005712.0000
892000.00NULLNULL0.0000

Without the fix, the rows with no rate give NULL, the same as before. With the fix they give 0.0000.

Zero. Not eight thousand. Zero, because zero is smaller than eight thousand, so LEAST picks it.

A cap that said at most eight thousand now says exactly nothing. Let's count it.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(LEAST(SALARY * ZEROIFNULL(COMMISSION_PCT), 8000) = 0) AS CAPPED_AT_ZERO,
       COUNT_IF(COMMISSION_PCT IS NULL) AS BECAUSE_THE_RATE_WAS_NULL
FROM EMPLOYEES;
Result1 row · 3 columns
ROWS_TOTALCAPPED_AT_ZEROBECAUSE_THE_RATE_WAS_NULL
855

8 rows, 5 capped at zero, and 5 rows where the rate was NULL. The same 5 again.

The lesson of this section

ZEROIFNULL is not a null fix. It is a statement that NULL means zero. The edit that rescued the floor destroyed the cap, and the SQL looks equally reasonable both times.

Is there something that just ignores the nulls?

There is, and it is the answer in both directions. GREATEST_IGNORE_NULLS and LEAST_IGNORE_NULLS exist.

Query
SELECT EMP_ID, COMMISSION_PCT,
       GREATEST_IGNORE_NULLS(SALARY * COMMISSION_PCT, 5000) AS GREATEST_IGNORE_NULLS_,
       LEAST_IGNORE_NULLS(SALARY * COMMISSION_PCT, 8000)    AS LEAST_IGNORE_NULLS_
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 4 columns
EMP_IDCOMMISSION_PCTGREATEST_IGNORE_NULLS_LEAST_IGNORE_NULLS_
1NULL5000.00008000.0000
2NULL5000.00008000.0000
30.055200.00005200.0000
4NULL5000.00008000.0000
50.109650.00008000.0000
6NULL5000.00008000.0000
70.085712.00005712.0000
8NULL5000.00008000.0000

On the rows with no rate, GREATEST_IGNORE_NULLS gives 5000.0000 and LEAST_IGNORE_NULLS gives 8000.0000. Both of those are right.

They took the only argument that was not NULL and used it, without us having to claim that the missing rate meant anything at all.

So if what you want is the null left out rather than turned into a number, these are the ones to reach for.

Now the null-safe comparisons

Last part of the post, and it is the one that catches people in production. Let's start with the comparison itself.

Query
SELECT NULL = NULL                 AS PLAIN_EQUALS,
       NULL = NULL IS NULL         AS THE_RESULT_IS_NULL,
       EQUAL_NULL(NULL, NULL)      AS EQUAL_NULL_,
       NULL IS NOT DISTINCT FROM NULL AS IS_NOT_DISTINCT_FROM,
       EQUAL_NULL(1, NULL)         AS ONE_VERSUS_NULL,
       EQUAL_NULL(1, 1)            AS ONE_VERSUS_ONE;
Result1 row · 6 columns · scroll →
PLAIN_EQUALSTHE_RESULT_IS_NULLEQUAL_NULL_IS_NOT_DISTINCT_FROMONE_VERSUS_NULLONE_VERSUS_ONE
NULLNULLTRUETRUEFALSETRUE

NULL = NULL is NULL. Not true, not false.

Now the second column, which is worth a moment because it does not say what it was meant to say. It is written NULL = NULL IS NULL, and it came back NULL as well — not TRUE.

The reason is how Snowflake reads it. The IS NULL attaches to the right-hand NULL first, so what actually ran was NULL = (NULL IS NULL), which is NULL = TRUE, which is NULL. A test written to show that a comparison returns NULL was itself defeated by the same rule. If you want to ask that question, wrap the comparison in brackets first.

The columns that do work are the next ones. EQUAL_NULL(NULL, NULL) is TRUE, and IS NOT DISTINCT FROM is TRUE too — that is the standard SQL spelling of the same idea.

And EQUAL_NULL(1, NULL) is FALSE. Properly false, not NULL. So we have a comparison that always answers.

A column that does not equal itself

Why does that matter? Because of this shape, which is what nearly every change-detection query looks like underneath.

Let's count the rows where the column equals itself. That should be all of them.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(COMMISSION_PCT = COMMISSION_PCT)            AS EQUALS_ITSELF,
       COUNT_IF(EQUAL_NULL(COMMISSION_PCT, COMMISSION_PCT)) AS EQUAL_NULL_ITSELF,
       COUNT_IF(NOT (COMMISSION_PCT = COMMISSION_PCT))      AS NOT_EQUALS_ITSELF,
       COUNT(*) - COUNT(COMMISSION_PCT)                     AS ACTUAL_NULLS
FROM EMPLOYEES;
Result1 row · 5 columns
ROWS_TOTALEQUALS_ITSELFEQUAL_NULL_ITSELFNOT_EQUALS_ITSELFACTUAL_NULLS
83805

3 out of 8.

A column does not equal itself on 5 rows, because on those rows it is NULL. EQUAL_NULL(x, x) gives 8, which is the answer you expected.

Now the fourth column, and this is the part that really hurts. It counts the rows where the column does not equal itself — the rows a job would call changed.

0. Because NOT (NULL) is also NULL, so those 5 rows fail that test too.

The changed test misses them and the unchanged test misses them. They fall straight through the gap, and a job built this way reports no changes for ever.

One last thing: the same gap in a WHERE clause

It is not only equality against itself. Any plain <> on a column that can be NULL has the same hole. Let's compare IS DISTINCT FROM 0 against <> 0, row by row.

Query
SELECT EMP_ID, COMMISSION_PCT,
       COMMISSION_PCT IS DISTINCT FROM 0        AS DISTINCT_FROM_ZERO,
       COMMISSION_PCT <> 0                      AS PLAIN_NOT_EQUALS,
       COMMISSION_PCT IS NOT DISTINCT FROM NULL AS IS_IT_NULL
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 5 columns
EMP_IDCOMMISSION_PCTDISTINCT_FROM_ZEROPLAIN_NOT_EQUALSIS_IT_NULL
1NULLTRUENULLTRUE
2NULLTRUENULLTRUE
30.05TRUETRUEFALSE
4NULLTRUENULLTRUE
50.10TRUETRUEFALSE
6NULLTRUENULLTRUE
70.08TRUETRUEFALSE
8NULLTRUENULLTRUE

On the rows with no rate, <> 0 is NULL and IS DISTINCT FROM 0 is TRUE. A WHERE clause keeps rows that are true, so the first spelling drops them and the second keeps them.

Query
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(COMMISSION_PCT <> 0)                  AS PLAIN_NOT_EQUALS_TRUE,
       COUNT_IF(COMMISSION_PCT IS DISTINCT FROM 0)    AS IS_DISTINCT_FROM_TRUE,
       COUNT_IF(COMMISSION_PCT IS DISTINCT FROM 0)
         - COUNT_IF(COMMISSION_PCT <> 0)              AS THE_DIFFERENCE
FROM EMPLOYEES;
Result1 row · 4 columns
ROWS_TOTALPLAIN_NOT_EQUALS_TRUEIS_DISTINCT_FROM_TRUETHE_DIFFERENCE
8385

3 rows against 8, and the difference is 5. Those 5 rows vanish from a plain <> without anything being filtered on purpose.

So when a column can be NULL, use IS DISTINCT FROM or EQUAL_NULL. Every time.

Here it all is on one grid, so you can see the shapes together.

Query
SELECT EMP_ID, SALARY, COMMISSION_PCT,
       ZEROIFNULL(COMMISSION_PCT)                                  AS RATE_OR_ZERO,
       NULLIFZERO(ZEROIFNULL(COMMISSION_PCT))                      AS BACK_TO_NULL,
       GREATEST(SALARY * ZEROIFNULL(COMMISSION_PCT), 5000)         AS BONUS_WITH_FLOOR,
       LEAST(SALARY * ZEROIFNULL(COMMISSION_PCT), 8000)            AS BONUS_WITH_CAP,
       EQUAL_NULL(COMMISSION_PCT, NULL)                            AS IS_IT_MISSING
FROM EMPLOYEES
ORDER BY EMP_ID;
Result8 rows · 8 columns · scroll →
EMP_IDSALARYCOMMISSION_PCTRATE_OR_ZEROBACK_TO_NULLBONUS_WITH_FLOORBONUS_WITH_CAPIS_IT_MISSING
1118000.00NULL0.00NULL5000.00000.0000TRUE
296500.00NULL0.00NULL5000.00000.0000TRUE
3104000.000.050.050.055200.00005200.0000FALSE
487250.00NULL0.00NULL5000.00000.0000TRUE
596500.000.100.100.109650.00008000.0000FALSE
6131000.00NULL0.00NULL5000.00000.0000TRUE
771400.000.080.080.085712.00005712.0000FALSE
892000.00NULL0.00NULL5000.00000.0000TRUE

The rate, the rate as zero, the round trip back to NULL, the bonus with a floor, the bonus with a cap, and a null-safe test for whether the rate is there at all.

Read the floor column against the cap column. They disagree on every row where IS_IT_MISSING is TRUE, which is the bug from the middle of this post. And they disagree on one row where it is FALSE as well — the row whose commission is above the cap, which is the floor and the cap doing exactly what they were asked to do.

Key points

  • ZEROIFNULL(x) is NVL(x, 0) and NULLIFZERO(x) is NULLIF(x, 0). Shorter names, identical behaviour.
  • The round trip between them is only safe when the column has no genuine zeros, so count them before you trust it.
  • GREATEST and LEAST work across columns on one row. MAX works down a column.
  • They compare according to type, so GREATEST('10', '9') is '9'.
  • Any NULL argument makes GREATEST and LEAST return NULL. They do not ignore it and take the biggest of the rest.
  • That is how a guaranteed minimum silently pays nothing to exactly the people it was written for.
  • Wrapping the value in ZEROIFNULL rescues a floor and ruins a cap. It is a statement about meaning, not a repair.
  • GREATEST_IGNORE_NULLS and LEAST_IGNORE_NULLS do the right thing in both directions.
  • NULL = NULL is NULL. EQUAL_NULL and IS NOT DISTINCT FROM are TRUE.
  • A column does not equal itself when it is NULL, so a changed test and an unchanged test can miss the same rows.
  • A plain <> drops the null rows from a WHERE clause. IS DISTINCT FROM keeps them.
Next in this series

Episode 82 — the context functions. CURRENT_USER, CURRENT_ROLE, CURRENT_DATABASE and IDENTIFIER, including the one line in a WHERE clause that turns a destructive statement into a harmless one.

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 EMPLOYEES data is invented demo data created by that script. The second column of the comparison grid is described as returning NULL rather than TRUE because that is the value the capture holds; the explanation of why is in that section. No performance or benchmark claims are made anywhere in this series. Function behaviour follows the Snowflake GREATEST documentation.

No comments:

Post a Comment

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