How to use the COALESCE function to handle NULL values in SQL queries?
How to use the COALESCE function to handle NULL values in SQL queries?
386
04-Sep-2023
Updated on 26-Sep-2023
Aryan Kumar
26-Sep-2023You can use the COALESCE function in SQL to handle null values in queries by returning the first non-null value from a list of expressions. It's particularly useful when you want to replace null values with a default value or a value from another column. Here's the syntax for the COALESCE function:
Here are a few common use cases for the COALESCE function:
Replace Null with a Default Value:
In this query, if price is null, it will be replaced with 0 in the result set.
Select the First Non-Null Value from Multiple Columns:
If first_name is null, it will display the value from last_name as full_name.
Handle Nested Nulls:
This query checks col1 first, and if it's null, it checks col2, and so on. If all columns are null, it returns 'No value'.
The COALESCE function is a powerful tool for handling null values and providing default values or alternate values in SQL queries, making your results more informative and user-friendly.