Beginner

190. NULLIF Function

Learn how NULLIF returns NULL when two expressions are equal.

📘 Lesson 190 of 728 ⏱ 9 min 🎯 Intermediate

NULLIF compares two expressions and returns NULL when they are equal; otherwise, it returns the first expression.

NULLIF can help handle special values and prevent issues such as division by zero in calculations.

NULLIF can convert a zero denominator into NULL before performing a division.

SQL
SELECT
    SalesAmount / NULLIF(UnitsSold, 0) AS AveragePrice
FROM Sales;

It is useful in financial calculations, ratios, data cleansing, exception handling, and preventing division-by-zero errors.

  • NULLIF compares two expressions.
  • It returns NULL when both expressions are equal.
  • Otherwise it returns the first expression.
  • It can help prevent division-by-zero errors.
  • It is useful for handling special values.
What does NULLIF do?

NULLIF returns NULL when its two expressions are equal; otherwise it returns the first expression.

How can NULLIF prevent division by zero?

NULLIF can convert a zero denominator to NULL so the calculation does not directly divide by zero.

Have you finished this lesson?

Introduction to SQL – All Lessons