What is the NULLIF function in PostgreSQL?
Overview
The NULLIF function in PostgreSQL is an in-built conditional function that takes two arguments and returns null if they equal one another. Otherwise, it returns only the first argument.
The function returns null if either of the arguments is null.
Syntax
NULLIF(arg_1, arg_2);
The function returns null if arg_1 is equal to arg_2, and returns arg_1 otherwise.
Example 1
| SQL | Output |
|---|---|
select nullif(1, 1); |
null |
select nullif(0, 1); |
0 |
select nullif('educative', 'edpresso') |
educative |
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 Name, COALESCE(NULLIF(Price, 1000), 0) as new_price from Product;
Explanation
- Lines 1–3: We define the
Producttable withNameandPriceas attributes. - Lines 6–11: We insert several records into the
Producttable. Here, we insert a record wherePriceisnull. - Line 14: We check whether the price of a product is equal to
1000. If the price is1000, theNULLIFfunction returnsnull. We choose0instead ofnullusing the COALESCE function.