SQL NULLIF() Function for Avoiding Division by Zero and Data Cleanup

🚀 SQL Tip: NULLIF() – Small Function, Big Use Case! Have you ever faced a situation where you need to avoid division by zero or want to convert a specific value into NULL? That’s where NULLIF() comes in handy. ✅ What NULLIF() does: It compares two expressions. If both are equal → returns NULL If not equal → returns the first expression 📌 Syntax: NULLIF(expression1, expression2) 🔥 Common Example: Avoid Division by Zero SELECT SalesAmount / NULLIF(Quantity, 0) AS AvgPrice FROM SalesTable; 👉 If Quantity = 0, NULLIF() returns NULL, and the division safely returns NULL instead of throwing an error. 🎯 Another Example: Convert unwanted values into NULL SELECT NULLIF(CustomerName, '') AS CleanCustomerName FROM Customers; This converts empty strings into NULL, which is useful in reporting and data cleanup. 💡 Why it’s useful? ✔ Prevent runtime errors ✔ Cleaner data handling ✔ Helpful in reporting calculations ✔ Makes queries more readable 📌 Pro Tip: NULLIF() is often used with COALESCE() for better default values. #SQL #SQLServer #Database #TSQL #DataEngineering #SQLTips

To view or add a comment, sign in

Explore content categories