Snowflake Vs MS-SQL - Part 41 - NVL2

         


NVL2

A table contains 3 columns, if the value in the first column is NOT NULL then you have to return/display the value from the second column and if the value in the first column is NULL then you have to return/display the value from the third column.

Suppose you have data as below:
--------+--------+--------+
Col1    | Col2   | Col3   |
--------+--------+--------+
 0      | 5      | 3      |
 0      | 5      | [NULL] |
 0      | [NULL] | 3      |
 0      | [NULL] | [NULL] |
 [NULL] | 5      | 3      |
 [NULL] | 5      | [NULL] |
 [NULL] | [NULL] | 3      |
 [NULL] | [NULL] | [NULL] |
--------+--------+--------+

Expected Output
--------+--------+--------+---------------+
Col1    | Col2   | Col3   | RESULT        |
--------+--------+--------+---------------+
 0      | 5      | 3      | 5             |
 0      | 5      | [NULL] | 5             |
 0      | [NULL] | 3      | [NULL]        |
 0      | [NULL] | [NULL] | [NULL]        |
 [NULL] | 5      | 3      | 3             |
 [NULL] | 5      | [NULL] | [NULL]        |
 [NULL] | [NULL] | 3      | 3             |
 [NULL] | [NULL] | [NULL] | [NULL]        |
--------+--------+--------+---------------+

MS-SQL Server 

You can achieve this by using the CASE Statement as follows. 



In Snowflake, we can use the same approach as above however Snowflake has a different conditional expression NVL2.


Note: If you want to display static values instead of Col2 & & Col3, then it also supports.
You can use nested as well.


For more details, you can refer to the following NVL2.




Comments

Popular posts from this blog

Snowflake Vs MS-SQL - Part 36 - SPLIT_TO_TABLE

Snowflake Vs MS-SQL - Part 63 - ON Clause & Cross Join

Snowflake Vs MS-SQL - Part 33 - INITCAP