
257 views
MySQL IFNULL()
The MySQL IFNULL() function is used to handle NULL values in expressions or columns. It returns the first non-NULL expression from a list of expressions provided as arguments. If all expressions are NULL, it returns NULL.
The basic syntax of the IFNULL() function is as follows:
IFNULL(expression1, expression2)
Here’s how it works:
expression1is the expression that the function evaluates. If it is notNULL, the function returnsexpression1.expression2is the fallback expression. Ifexpression1isNULL, the function returnsexpression2.
The IFNULL() function is especially useful for handling NULL values and providing default values when a column or expression is NULL.
Here are some examples to illustrate the use of the IFNULL() function:
- Use the
IFNULL()function to replaceNULLvalues in thediscountcolumn with a default discount of 0:
SELECT product_name, IFNULL(discount, 0) AS final_discount
FROM products;
- Use the
IFNULL()function to return the first non-NULLvalue from a list of expressions:
SELECT customer_name, IFNULL(phone_number, email, 'No contact information available') AS contact_info
FROM customers;
- Calculate the total price of an order, taking into account that the
discountmight beNULL:
SELECT order_id, product_name, quantity, unit_price, IFNULL(discount, 0) AS applied_discount,
quantity * unit_price * (1 - IFNULL(discount, 0)) AS total_price
FROM order_details;
The IFNULL() function is a helpful tool for handling NULL values in SQL queries, allowing you to provide meaningful defaults or perform calculations while gracefully dealing with missing or undefined data.