You 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:
expression1, expression2, expression3, and so on are the values or columns you want to evaluate. The function returns the first non-null expression from left to right.
Here are a few common use cases for the COALESCE function:
Replace Null with a Default Value:
Suppose you have a column named price, and you want to display a default value of 0 when it's null:
SELECT COALESCE(price, 0) AS adjusted_price
FROM products;
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:
You can use COALESCE to select the first non-null value among multiple columns. For example, if you have columns
first_name and last_name and you want to display the first non-null name:
SELECT COALESCE(first_name, last_name) AS full_name
FROM users;
If first_name is null, it will display the value from
last_name as full_name.
Handle Nested Nulls:
You can nest COALESCE functions to handle situations where multiple columns may contain null values:
SELECT COALESCE(col1, COALESCE(col2, col3, col4, 'No value')) AS result
FROM your_table;
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You 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.