What is COALESCE in PostgreSQL?
Overview
COALESCE in PostgreSQL is an in-built function that returns the first non-null value/expression in the given list of values/expressions.
Parameters
- The function takes unlimited arguments.
- The
COALESCEfunction expects the arguments to be of the same datatype. Otherwise, it throws an error.
Return value
This function returns the first non-null argument.
Syntax
COALESCE (arg_1, arg_2, arg_3, …);
The evaluation of the function is from left to right. In the syntax above, the null check will be performed for arg_1, then for arg_2.
Code example 1
Let’s look at the code below:
SELECT COALESCE(NULL, 'educative', 'edpresso', NULL, 'hello') as coalesce_output;
Code explanation
In the above example, we pass different arguments to the COALESCE() function. Some of the observations are:
- The output is
educative. It is the first non-null argument. - Once the function reaches the second argument, that is,
educative, further arguments are ignored.
Code example 2
Let’s look at another example:
CREATE TABLE Product (Name varchar(100) NOT NULL,Price int);INSERT INTO Product(Name, Price)VALUES ('mobile', 120),('TV', 200),('Remote', NULL),('Laptop', 1000);select *, COALESCE(Price, 0) * 0.05 as Discount from Product;
Code explanation
- Lines 1 to 3: We define the
Producttable withNameandPriceas attributes. - Lines 6 to 11: We insert several records into the
Producttable. Here, we insert a record wherePriceisNULL. - Line 13: We calculate the discount in the
Pricecolumn. Here, theCOALESCE()function is used with argumentsPriceand0. So0is returned when anyPricevalue isNULL.