Understanding NULLIF Function Behavior in PostgreSQL
📖 Scenario: You are managing a small online store database. Sometimes, the discount applied to a product is the same as the product price, which means the final price should be considered as NULL to indicate no effective price.
🎯 Goal: Build a simple query using the NULLIF function to return NULL when the discount equals the product price, otherwise return the product price.
📋 What You'll Learn
Create a table called
products with columns product_id (integer), product_name (text), price (numeric), and discount (numeric).Insert exactly three rows into
products with the following data: (1, 'Pen', 10, 5), (2, 'Notebook', 20, 20), (3, 'Eraser', 5, 0).Write a SELECT query that uses
NULLIF to return final_price which is NULL if price equals discount, otherwise returns price.Ensure the query returns
product_id, product_name, and final_price.💡 Why This Matters
🌍 Real World
NULLIF is useful in databases to handle cases where certain values should be treated as missing or undefined, such as when discounts equal prices.
💼 Career
Understanding NULLIF helps in writing clean SQL queries for data cleaning, reporting, and business logic implementation in real-world database jobs.
Progress0 / 4 steps