The PostgreSQL COALESCE() function is used to handle NULL values by evaluating multiple expressions and returning the first available non-NULL value. It helps produce more meaningful query results and simplifies working with nullable data in PostgreSQL.
- Improve the readability and maintainability of SQL queries.
- Work efficiently with nullable columns in database tables.
Syntax
COALESCE(expression_1, expression_2, ..., expression_n)Where:
- expression_1: The first expression to be evaluated. If it is not NULL, the COALESCE() function returns its value immediately.
- expression_2, expression_3, ...: Additional expressions that are evaluated only if the preceding expressions are NULL.
- expression_n: The last expression in the list. It is returned only if all the previous expressions are NULL.
Working
Firstly, create a sales table and insert some records.

Example 1: Calculate the Final Bill Without COALESCE()
The following query calculates the final bill without using the COALESCE() function.
Query:
SELECT product_name,
amount - discount AS final_bill
FROM sales;
Output:

- Since the discount value for Coffee is NULL, the calculation also returns NULL.
Example 2: Replace NULL Values Using COALESCE()
The following query replaces the NULL discount with 0 before performing the calculation.
Query:
SELECT product_name,
amount - COALESCE(discount, 0) AS final_bill
FROM sales;
Output:

- The COALESCE() function replaces the NULL discount with 0. As a result, PostgreSQL correctly calculates the final bill for Coffee as 500.
Example 3: Using COALESCE() with CASE Expression
The following query achieves the same result using the CASE expression.
Query:
SELECT product_name,
amount -
CASE
WHEN discount IS NULL THEN 0
ELSE discount
END AS final_bill
FROM sales;
Output:

- The CASE expression checks whether the discount value is NULL. If it is, 0 is used; otherwise, the original discount is used.
- Both CASE and COALESCE() produce the same result, but COALESCE() is shorter and easier to read.

