简体   繁体   中英

In what scenario the second/third non-null parameters will be returned in COALESCE mysql?

[The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.] https://www.sqlshack.com/using-the-sql-coalesce-function-in-sql-server/

Why bother adding second/third non-null paramaters or just use IFNULL() instead, if it will always return the first non-null parameter?

First, COALESCE() is Standard SQL. My recommendation is to use the standard SQL function, unless you have a reason to use a bespoke function such as IFNULL() .

Second, IFNULL() is limited to two arguments. COALESCE() is more powerful because it can take any number of arguments.

Coalesce returns first non-null value in the list of arguments, if the first argument is null. These list of arguments could be constant value or derivation of other column value.

Primarily used for scenarios where you have to derive value from some other column or replace null with value for column where null is not an accepted for a given column.

Example: If a column is representing discount% then the value could be either a value or 0.0 but cannot be null.

coalesce(special_discount,base_discount_column,0.05) 

Here special discount if null consider base discount value, if base discount is also null, then take 5% discount by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM