COALESCE function in SQL

Posted on Dec 26, 2023

The COALESCE function in SQL returns the first non-null value in a list. It takes at least two arguments, which can be expressions or column names.

It is broadly supported across relational databases like MySQL, PostgreSQL, and SQL Server, as well as data warehouses like Snowflake, Redshift, and Hive.

For example:

COALESCE(NULL, NULL, 'third value', 'fourth value')

Would return:

'third value'

Since the first two arguments are NULL, COALESCE returns the first non-null value in the list.

Some key properties of COALESCE:

  • It can take an unlimited number of arguments.
  • The arguments must be of the same or compatible data types. Trying to compare different data types will result in an error.
  • The return type is the same as the input arguments.
  • NULL values are ignored.
  • If all arguments are NULL, it will return NULL.

COALESCE is very handy for dealing with NULLs in SQL. Some examples:

- Replace NULL values:

SELECT COALESCE(NULL, 'N/A') 

Returns 'N/A'

- Fallback to default value:

SELECT COALESCE(commission, 0) FROM employees

Returns 0 for null commissions

- Handling nulls in calculations:

SELECT COALESCE(SUM(sales), 0) FROM data

Avoids error from the null sum

- Combining columns:

SELECT COALESCE(col1, col2) AS combined_column FROM table

- Chaining multiple functions:

SELECT COALESCE(RTRIM(LTRIM(col)), '')

Trims whitespace, falling back to an empty string if null

The advantage of COALESCE over ISNULL is that it can take multiple arguments, not just two.

Some typical use cases for COALESCE:

  • Populate default values for nullable columns
  • Fallback to default values in calculations
  • Concatenating text columns with separator
  • Implement variable substitution logic
  • Merge data from multiple sources
  • Improve readability over nested ISNULL calls

An alternative in some databases is the IFNULL function, which serves the same purpose. The syntax is:

IFNULL(expr1, expr2) 

However, IFNULL only takes two arguments, which is less flexible than COALESCE.

In summary, COALESCE is a convenient SQL function for gracefully handling null values. Its ability to accept multiple arguments simplifies queries and handles edge cases where you want to fall back to default values. This helps avoid errors and unexpected null outputs. Anytime you work with nullable SQL columns, consider using COALESCE as part of your toolkit.

©2024 SQLZap - Learn SQL Interactively

Twitter