
MySQL NULLIF()
The MySQL NULLIF()
function is used to compare two expressions and return NULL
if they are equal, and if they are not equal, it returns the first expression. This function is often used to handle cases where you want to treat certain values as NULL
or replace them with NULL
.
The basic syntax of the NULLIF()
function is as follows:
NULLIF(expression1, expression2)
Here’s how it works:
expression1
is the first expression to be compared.expression2
is the second expression to be compared.- If
expression1
is equal toexpression2
, the function returnsNULL
. - If
expression1
is not equal toexpression2
, the function returnsexpression1
.
Here are some examples to illustrate the use of the NULLIF()
function:
- Set a column to
NULL
if its value is “Unknown”:
SELECT employee_name, NULLIF(job_title, 'Unknown') AS normalized_job_title
FROM employees;
- Replace a value with
NULL
if it matches a specific value:
SELECT product_name, NULLIF(unit_price, 0) AS price
FROM products;
- Handle cases where a division by zero might occur:
SELECT order_id, total_amount / NULLIF(quantity, 0) AS unit_price
FROM orders;
In the third example, NULLIF(quantity, 0)
is used to prevent division by zero. If the quantity
is zero, the function returns NULL
, avoiding a division error.
The NULLIF()
function is a valuable tool when you want to replace or treat certain values as NULL
in your SQL queries, especially in cases where you need to handle special conditions gracefully.