In PostgreSQL, the COALESCE function returns the first non-null argument. It is generally used with the SELECT statement to handle null values effectively.
Syntax: COALESCE (argument_1, argument_2, …);
The COALESCE function accepts an unlimited number of arguments. It returns the first argument that is not null. If all arguments are null, the COALESCE function will return null. he COALESCE function evaluates arguments from left to right until it finds the first non-null argument. All the remaining arguments from the first non-null argument are not evaluated.
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,
There are four fields in the
- 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 INSERT statement as follows:
INSERT INTO items (product, price, discount)
('A', 1000, 10),
('B', 1500, 20),
('C', 800, 5),
('D', 500, NULL);
Finally we query the net prices of the products using the following:
(price - discount) AS net_price
This will lead to the following:
f 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:
(price - COALESCE(discount, 0)) AS net_price
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!