In Snowflake, the COALESCE function is used to return the first non-null expression from a list of expressions. It is commonly used to handle null values and provide a fallback value when encountering nulls. Here’s the syntax for the COALESCE function in Snowflake:
COALESCE(expr1, expr2, …)
The COALESCE function takes two or more expressions as arguments and returns the first non-null expression. It evaluates the expressions in order from left to right and returns the value of the first non-null expression. If all expressions are null, the COALESCE function returns null.
SELECT COALESCE(column1, column2, ‘N/A’) AS result FROM table;
In this query, if **`column1`** is not null, its value will be returned. If **`column1`** is null but **`column2`** is not null, the value of **`column2`** will be returned. If both **`column1`** and **`column2`** are null, the COALESCE function will return the fallback value **`’N/A’`**.
The COALESCE function is helpful when you need to provide a default or substitute value for null expressions. It allows you to handle null values in a concise and controlled manner, ensuring that a valid result is always returned.
By using the COALESCE function, you can simplify your queries and expressions by handling nulls effectively and providing alternative values or defaults when necessary.