sql / intermediate
Snippet
Handling Null Values Safely with COALESCE
The ANSI SQL standard COALESCE function evaluates arguments sequentially from left to right and returns the first non-NULL value. It prevents unexpected NULL results in calculations and reporting.
snippet.sql
sql
1
2
3
4
5
SELECTproduct_id,product_name,COALESCE(discount_price, list_price, 0.00) AS effective_priceFROM products;
Breakdown
1
COALESCE(discount_price, list_price, 0.00) AS effective_price
Evaluates arguments in left-to-right order and returns the first non-NULL value.
2
discount_price,
First priority price column checked for existence of a value.
3
list_price,
Fallback price evaluated when discount_price contains NULL.
4
0.00)
Default non-NULL literal returned if all prior expressions evaluate to NULL.