LogoInterview Master

SQL Learning Hub

SQL COALESCE Function

Understanding the SQL COALESCE Function

The COALESCE function in SQL returns the first non-NULL expression in a list of expressions. It's an essential tool for handling NULL values and providing default values in your queries.

Basic Syntax

COALESCE Step-by-Step Evaluation

  1. It checks expression1. If it's not NULL, its value is returned, and evaluation stops.
  2. If expression1 is NULL, it checks expression2.
  3. If expression2 is not NULL, its value is returned, and evaluation stops.
  4. If expression2 is NULL, it proceeds to expression3, and so on.
  5. This continues until a non-NULL expression is found or the end of the list is reached.
  6. If all expressions in the list are NULL, COALESCE returns NULL.

Common SQL COALESCE Interview Questions

  • How does COALESCE handle a list of all NULL values?
  • What's the difference between COALESCE and IFNULL/NVL?
  • How can COALESCE improve query readability and maintainability?
  • Can COALESCE handle different data types in the same expression?

How COALESCE Works

Basic COALESCE Usage

COALESCE evaluates expressions in order and returns the first non-NULL value it encounters.

Note: If all expressions evaluate to NULL, COALESCE will return NULL as the result.

Data Type Compatibility

All expressions in COALESCE should have compatible data types. The data type of the returned value is determined based on data type precedence rules (usually the "highest" precedence type among the non-NULL arguments). It's best practice to ensure all potential return values are of compatible types or to explicitly cast them.

Providing Default Values for Columns

One of the most common uses of COALESCE is to provide default values for NULL columns in results.

COALESCE vs. IFNULL/NVL

COALESCE is more flexible than database-specific NULL-handling functions. Advantage: COALESCE is part of the SQL standard and works across different database systems, whereas functions like IFNULL (MySQL) and NVL (Oracle) are database-specific.

Comparison of NULL-Handling Approaches

Function/SyntaxProsConsExample
COALESCE✓ Standard SQL
✓ Handles multiple fallbacks
✓ Generally readable
Evaluates arguments sequentiallyCOALESCE(col1, col2, "Def")
CASE WHEN✓ Standard SQL
✓ Handles complex logic
More verbose for simple NULL replacementCASE WHEN col1 IS NULL THEN "Def" ELSE col1 END
ISNULL (SQL Server)✓ Concise for single fallback✗ SQL Server specific
✗ Only two arguments
ISNULL(col1, "Def")
NVL (Oracle)✓ Concise for single fallback✗ Oracle specific
✗ Only two arguments
NVL(col1, "Def")
IFNULL (MySQL, SQLite)✓ Concise for single fallback✗ Non-standard
✗ Only two arguments
IFNULL(col1, "Def")

Advanced COALESCE Techniques

Order of Preference Data Selection

COALESCE can implement a preference order for selecting data.

Explanation: This first tries to use the user's email, then falls back to username, and finally uses a combination of user_id and username.

Using COALESCE with Aggregates

COALESCE works well with aggregate functions to handle NULL values in grouping operations.

In this example, if the views column is NULL, it will be replaced with 0 before the aggregation.

Dynamic Default Values

The default value in COALESCE can be a dynamic expression or subquery.

Note: This uses a correlated subquery to provide a user-specific average as the default.

Practical SQL COALESCE Examples

Example 1: User Profile Completeness Report

This example calculates the completeness of user profiles while handling NULL values:

Example 2: Video Analytics Dashboard

This example uses COALESCE to handle NULL metrics when building an analytics dashboard:

Example 3: Payment Processing with Fallbacks

This example demonstrates using COALESCE to implement interaction data fallbacks:

Best Practices for COALESCE

1. Keep Type Consistency

While COALESCE can handle mixed types (with implicit conversion), it's best practice to maintain consistent data types within a COALESCE expression to avoid unexpected type conversions.

2. Order Arguments by Performance

Since COALESCE evaluates arguments in order, for performance reasons, place frequently non-NULL values first and expensive expressions (like subqueries) later in the argument list.

3. Combine with Other Functions

COALESCE works well when combined with other functions like NULLIF or conditional expressions like CASE WHEN to handle complex NULL-handling scenarios.

4. Use for Cross-Database Compatibility

Prefer COALESCE over database-specific functions like IFNULL, NVL, or ISNULL for better cross-database compatibility.

Test Your Knowledge

Take a quick quiz to reinforce what you've learned about SQL COALESCE Function

Ready for hands-on SQL practice?

We have 200+ questions on real companies and real products.

Find a question to practice
Dawn AI