PostgreSQL COALESCE
Last Updated :
22 Jul, 2024
Handling NULL values effectively is crucial in database management, and PostgreSQL offers a powerful function called COALESCE to address this issue. The COALESCE function returns the first non-null argument among its parameters, making it particularly useful in SELECT statements.
Let us better understand the syntax, usage, and practical examples of the COALESCE function, helping you master its application in PostgreSQL.
Syntax
COALESCE (argument_1, argument_2, …);
Key Features
- Unlimited Arguments: You can provide as many arguments as you need to the COALESCE function.
- Returns First Non-NULL Value: COALESCE evaluates each argument in the order they are provided and returns the first one that is not NULL.
- Returns NULL if All Are NULL: If all arguments are NULL, COALESCE will return NULL.
- Short-Circuit Evaluation: Once COALESCE finds a non-NULL value, it stops evaluating the remaining arguments. This can improve performance in certain scenarios.
PostgreSQL COALESCE Examples
For the purpose of demonstration let’s first create a table (say, ‘items') using the below statement:
CREATE TABLE items (
ID serial PRIMARY KEY,
product VARCHAR (100) NOT NULL,
price NUMERIC NOT NULL,
discount NUMERIC
);
There are four fields in the items table:
- ‘id’:the primary key that identifies the item in the items table.
- ‘product’: the product name.
- ‘price’: the price of the product.
- ‘discount’: the discount of the product.
Now we insert some records into the items table using statement as follows:
INSERT INTO items (product, price, discount)
VALUES
('A', 1000, 10),
('B', 1500, 20),
('C', 800, 5),
('D', 500, NULL);
Finally we query the net prices of the products using the following:
SELECT
product,
(price - discount) AS net_price
FROM
items;
This will lead to the following:

If you look at the fourth row, you will notice that the net price of the product D is null which seems not correct. The issue is the discount of the product D is null, therefore when we take the null value to calculate the net price, PostgreSQL returns null. The get the right price, we need to assume that if the discount is null, it is zero.
Then we can use the COALESCE function as follows:
SELECT
product,
(price - COALESCE(discount, 0)) AS net_price
FROM
items;
Output:

Important Points About PostgreSQL COALESCE Function
- COALESCE uses short-circuit evaluation. This means it stops evaluating arguments as soon as it encounters the first non-null value.
- COALESCE can be used not only with simple columns but also with complex expressions, subqueries, and functions, making it highly versatile in various scenarios.
- If all the arguments provided to COALESCE are null, the function will return null. This is useful for creating fallback mechanisms in your queries.
- COALESCE can be employed in JOIN conditions to handle nullable columns, ensuring that null values do not disrupt the join logic.