MySQL

Chapter 7 - DQL (Data Query Language)

COALESCE

In MySQL, the COALESCE function is used to return the first non-NULL value from a list of expressions. It’s particularly useful when you’re dealing with fields that may contain NULL values and you want to ensure that your query returns a meaningful result. If all expressions evaluate to NULL, COALESCE will return NULL.

Here’s how the COALESCE function works, along with examples for new students:

  1. Basic Syntax of COALESCE():

    • The COALESCE() function takes two or more arguments and returns the first non-NULL value.
    • Syntax:
    SELECT COALESCE(NULL, 'Fallback Value') AS result;
    • This query returns 'Fallback Value' because the first argument is NULL.
  2. Using COALESCE() to Handle NULL Values:

    • You can use COALESCE() to provide a default value when a column contains NULL.
    • Example:
    SELECT first_name, last_name, COALESCE(salary, 0) AS salary FROM employees;
    • This query replaces NULL values in the salary column with 0.
  3. Handling Multiple Columns with COALESCE():

    • You can use COALESCE() to choose the first non-NULL value from multiple columns.
    • Example:
    SELECT first_name, COALESCE(phone_number, email, 'No Contact') AS contact_info FROM employees;
    • This query retrieves the phone number, but if it’s NULL, it retrieves the email. If both are NULL, it returns 'No Contact'.
  4. Using COALESCE() with Calculations:

    • You can apply COALESCE() to numeric fields, ensuring that your calculations don’t fail due to NULL values.
    • Example:
    SELECT first_name, last_name, COALESCE(bonus, 0) + salary AS total_compensation FROM employees;
    • This query calculates total compensation, ensuring that the bonus is treated as 0 if it’s NULL.
  5. Replacing NULL in Concatenations:

    • COALESCE() can be useful when concatenating strings that might contain NULL values.
    • Example:
    SELECT CONCAT(first_name, ' ', COALESCE(middle_name, ''), ' ', last_name) AS full_name FROM employees;
    • This query ensures that the middle_name is treated as an empty string if it’s NULL, so the CONCAT function still works.
  6. Using COALESCE() with Subqueries:

    • You can use COALESCE() with subqueries to provide default values when subqueries return NULL.
    • Example:
    SELECT first_name, last_name, COALESCE((SELECT bonus FROM bonuses WHERE employee_id = e.employee_id), 0) AS bonus FROM employees e;
    • This query assigns a default bonus of 0 if the subquery does not return a value.
  7. Using COALESCE() in ORDER BY:

    • You can use COALESCE() in the ORDER BY clause to ensure that NULL values don’t affect the sorting of results.
    • Example:
    SELECT first_name, last_name, salary FROM employees ORDER BY COALESCE(salary, 0) DESC;
    • This query sorts employees by salary in descending order, treating NULL salaries as 0.
  8. COALESCE() with Multiple Arguments:

    • You can pass multiple arguments to COALESCE() to check several columns or expressions in order.
    • Example:
    SELECT first_name, COALESCE(phone_number, email, address, 'No Contact Info') AS contact_info FROM employees;
    • This query checks for the first non-NULL value in the phone_number, email, and address columns.
  9. Performance Considerations:

    • While COALESCE() is a powerful function, excessive use in large datasets may impact performance. Be mindful of its application in performance-critical queries.

The COALESCE function is an excellent tool for handling NULL values and ensuring that your query returns usable results even when some data is missing. It’s a versatile function, allowing you to provide fallback values and manage NULL values gracefully in your queries.

Tansy SQL Course | COALESCE | Chapter 7 | Lesson 40 - Video Thumbnail

Test code

Replace descriptions with the string 'Not provided' wherever the description is null.

SELECT product_id, product_name, COALESCE(description,'Not Provided') 
FROM prd_product ORDER BY product_id;
Try it now

RDBMS Overview

TheCOALESCEfunction in SQL returns the first non-null expression among its arguments. This function is useful for handling cases where data may be missing and a default value is needed.


Syntax of COALESCE

COALESCE(expression1, expression2, ..., expressionN)
  • The function evaluates the expressions in order.
  • It returns the first non-null expression.
  • If all expressions are null,COALESCEreturns null.

Example Usage of COALESCE

Here's an SQL query example usingCOALESCE:

SELECT COALESCE(address, phone, email, 'Unknown') AS contact_info FROM customers;

This example attempts to find the first non-null contact information for each customer and defaults to 'Unknown' if all are null.


COALESCE with LEFT JOIN

COALESCEcan be used withLEFT JOINto provide a default value when the joined table has no match:

SELECT customers.name, COALESCE(orders.order_number, 'No Orders') as order_info
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;

In this scenario, if a customer has no orders, 'No Orders' is returned instead of null.

COALESCE EXAMPLE

i

Here, we are attempting to substitute descriptions with the string 'Not provided' in cases where the description is null.

i

Please note that the query has successfully replaced null descriptions for product IDs 3 and 6 with the desired string 'Not Provided'. However, descriptions for product IDs 7 and 9 remain as empty strings. It's important to differentiate between an empty string and NULL. Our query was designed to replace NULL values, not empty strings.

Comments(0 comments)

Comments Not Found