top of page
Writer's pictureCharishma Chadalavada

The COALESCE() Function in PostgreSQL

When I was learning PostgreSQL, I encountered a situation to handle NULL values. At that time I assumed NULL was equal to zero or blank value, but later after researching this  I came to know that NULL, zero, and blank are three different terms in PostgreSQL, they are not the same. Handling NULL values in databases is a challenge because they are unknown values and these may create ambiguity in the data, especially in calculations or when generating reports. PostgreSQL provides a powerful function to handle this scenario with the COALESCE() function.




What is the COALESCE() Function?


COALESCE() in PostgreSQL is a system in-built function that is a conditional expression. It takes in a series of arguments and returns the first value that is not NULL. If all values are NULL, then it returns NULL. This makes it a very useful function when trying to handle missing data.


Syntax:


COALESCE(value1, value2,., value_n)


The COALESCE() function takes at least one value (value1). It will return the first value in the list if it is not null otherwise it will check the next value(value2) and it goes on untill the list is complete.

The COALESCE() function evaluates in the order from left to write,and it stops the process as it finds the first non-null value.

We can pass a mix of column names,literal values and expressions as arguments for the Coalesce() function.


Example 1: This example shows how the coalesce function returns the first non-null value.  

Select COALESCE(null,5,2);

In this case as the first non-null value is 5 ,it returns the second value 5.


Example 2:This example shows how the coalesce function works in case of both the arguments as non-null:

Select COALESCE(3,5);

In this case it returns the first argument 3, as both are non-null.


What are the Use Cases of COALESCE() ?


Firstly, Coalesce is mostly used in cases where we need to replace NULL values with meaningful default values. For example, in an orders table, which has a column that has data on the quantity of product each customer made, replacing a NULL value with a zero as the default value makes the tables clearer for analysis.


SELECT product_id, 

    COALESCE(quantity, 0) AS quantity

FROM products;


This query will ensure that any NULL value in the quantity column will be replaced by 0 to make the data easy and clean for analysis.


Secondly, in cases where we get our values from multiple columns of the table and in order to tackle null values ,we often use Coalesce function. For example, lets consider some customers table which has different columns for personal and work email. If we are checking if all customers have either one email id provided or not ,we may consider the usage of coalesce function.The querry can be written as follows:


SELECT user_id, 

    COALESCE(personal_email, work_email, 'No Email Provided') AS primary_email

FROM users;


This query returns the first non-NULL email or a default message if both columns are NULL. In this way we get the list of customers with 'No Email Provided’ very easily.


Handling Calculations with Missing Data is yet another usage of the COALESCE() function. When performing calculations, NULLs can result in the expression returning NULL. The COALESCE() function allows calculations to continue with a default value:


SELECT product_id,

price * COALESCE(discount_rate, 1) AS final_price

FROM products;


Here, if discount_rate is NULL, it defaults to 1, leaving the price unchanged.


This is one another example for the usage of coalesce function.


SELECT employee_id, 

    COALESCE(first_name || ' ' || last_name, 'Name Not Available') AS full_name

FROM employees;


This query concatenates first_name and last_name into a full name or returns a message 'Name Not Available' in case both of them are NULL.


COALESCE() is similar to CASE in behaviour ,but it is more concise and clear.


Using COALESCE:

SELECT COALESCE(column1, column2, 'Default') AS result;


Using CASE:

SELECT 

    CASE

WHEN column1 IS NOT NULL THEN column1 

        WHEN column2 IS NOT NULL THEN column2 

        ELSE 'Default' 

    END AS result;


As seen above, COALESCE() reduces verbosity while maintaining clarity.


Although COALESCE() is efficient with small lists of values ,its use with too many arguments can impact performance in complex queries and we must always ensure all arguments have compatible data types to avoid type-casting errors.


Conclusion

The COALESCE() function in PostgreSQL is an indispensable tool for handling NULL values. Its simplicity, flexibility, and efficiency make it ideal for a wide range of applications, from replacing missing values to implementing fallback logic. By embedding COALESCE() into your queries, you can make your data more consistent, reliable, and user-friendly.


Besides COALESCE(), PostgreSQL provides other functions to deal with NULL values, such as NULLIF() and CASE expressions. NULLIF() returns NULL if two given values are equal, while the CASE expression allows for more custom conditional logic. However, COALESCE() has a unique advantage in being concise and handling multiple arguments with ease. Together, these functions can be used to construct robust and efficient database queries.

5 views
bottom of page