SQL Tutorial

SQL Clauses / Operators

SQL-Injection

SQL Functions

SQL Queries

PL/SQL

MySQL

SQL Server

Misc

MySQL | IFNULL

In MySQL, the IFNULL() function is used to return an alternative value if the first expression is NULL. Essentially, it helps you avoid NULL values in your results by providing a default value when a NULL value is encountered.

Syntax:

IFNULL(expression1, expression2)

If expression1 is NULL, IFNULL() returns expression2; otherwise, it returns expression1.

Examples:

  1. Basic Usage:

    Let's say we have a table called products with a column discount_price and we want to display the discount_price for each product, but if the discount_price is NULL, we want to display 0 instead:

    SELECT product_name, IFNULL(discount_price, 0) as discount
    FROM products;
    
  2. Using with mathematical operations:

    Imagine you want to calculate the final price of a product by subtracting the discount from the original price. But if the discount is NULL, you'd want to treat it as 0:

    SELECT product_name, (price - IFNULL(discount_price, 0)) as final_price
    FROM products;
    
  3. Combining with other functions:

    You can also combine IFNULL with other SQL functions. For example, if you want to get the average discount, but treat NULL values as 0:

    SELECT AVG(IFNULL(discount_price, 0))
    FROM products;
    

IFNULL is quite useful when working with data that may contain NULL values and you want to provide a default value in such cases. If you're coming from other database systems, you might find similar functions like COALESCE or ISNULL (in SQL Server) which provide comparable functionality.

  1. How to Use IFNULL in MySQL:

    SELECT IFNULL(column_name, 'Default_Value') AS result
    FROM your_table;
    
  2. Handling NULL Values with IFNULL:

    SELECT column1, IFNULL(column2, 'N/A') AS result
    FROM your_table;
    
  3. Using IFNULL in SELECT Statements:

    SELECT column1, IFNULL(column2, 0) AS result
    FROM your_table;
    
  4. IFNULL in Conjunction with Other Functions:

    SELECT column1, IFNULL(CONCAT(column2, ' - ', column3), 'Not Available') AS result
    FROM your_table;
    
  5. Applying IFNULL to Multiple Columns in MySQL:

    SELECT IFNULL(column1, column2) AS result
    FROM your_table;
    
  6. Using IFNULL in WHERE Clauses:

    SELECT *
    FROM your_table
    WHERE IFNULL(column1, 'Unknown') = 'Unknown';
    
  7. IFNULL and Default Values in MySQL:

    SELECT column1, IFNULL(column2, column3) AS result
    FROM your_table;
    
  8. Nesting IFNULL Functions in MySQL:

    SELECT IFNULL(IFNULL(column1, column2), 'Default') AS result
    FROM your_table;
    
  9. IFNULL and Aggregate Functions in MySQL:

    SELECT AVG(IFNULL(column1, 0)) AS average_value
    FROM your_table;