Menu

How the coalesce() function works in SQLite?

Learn how SQLite coalesce() chooses the first non-NULL value, when it stops evaluating, and how it relates to ifnull().

Posted on By Updated on
On this page

Dealing with NULL values is an inevitable part of working with databases, and SQLite’s coalesce() function is your trusty tool for handling these missing data points gracefully. Think of coalesce() as a safety net that catches NULL values before they can cause problems in your queries, replacing them with meaningful alternatives you specify. Whether you’re cleaning up data, calculating values, or preparing reports, this function helps ensure your results make sense even when some data is missing.

The Essence of coalesce()

At its core, coalesce() returns the first non-NULL argument from a list you provide. SQLite evaluates the arguments from left to right and stops when it finds a non-NULL value. If all arguments are NULL, it returns NULL. SQLite changed its expression factoring in version 3.32.0 to ensure short-circuit execution of coalesce(); see the SQLite source check-in.

Here’s the basic syntax:

SELECT coalesce(expression1, expression2, ..., expressionN);

Providing Default Values for NULLs

The most common use of coalesce() is substituting NULL values with sensible defaults. Imagine a user profile table where some users haven’t set their display names:

SELECT
    user_id,
    coalesce(display_name, username, 'Anonymous') AS shown_name
FROM users;

In this example, the query first tries to use the display_name, falls back to username if that’s NULL, and finally uses ‘Anonymous’ if both are NULL. This ensures every user gets a readable name in the output.

Safeguarding Calculations Against NULL

NULL values can silently break mathematical operations, turning what should be simple calculations into NULL results. coalesce() acts as a protective wrapper:

SELECT
    product_name,
    price,
    discount,
    price - coalesce(discount, 0) AS final_price
FROM products;

Here, if a product has no discount (NULL), we treat it as zero to prevent the entire calculation from becoming NULL. This keeps your reports clean and meaningful.

Simplifying Complex Conditional Logic

While SQLite has CASE WHEN for conditional logic, coalesce() often provides a more elegant solution for NULL handling:

-- Using CASE
SELECT
    CASE
        WHEN address IS NOT NULL THEN address
        WHEN backup_address IS NOT NULL THEN backup_address
        ELSE 'No address on file'
    END AS shipping_address
FROM customers;

-- Using coalesce (cleaner!)
SELECT
    coalesce(address, backup_address, 'No address on file') AS shipping_address
FROM customers;

The coalesce() version accomplishes the same goal with less code and clearer intent.

Combining with Other Functions for Powerful Transformations

coalesce() really shines when combined with other SQLite functions. Here’s an example that formats dates while handling NULLs:

SELECT
    order_id,
    coalesce(strftime('%Y-%m-%d', shipment_date), 'Not shipped yet') AS shipment_status
FROM orders;

Or consider this example that handles potentially NULL numeric data before formatting:

SELECT
    product_name,
    '$' || coalesce(cast(price AS TEXT), 'Price not set') AS price_display
FROM inventory;

Handling Multiple Fallback Layers

One of coalesce()’s strengths is its ability to chain multiple fallback options. This is particularly useful in hierarchical data structures:

SELECT
    employee_id,
    coalesce(
        custom_email,
        work_email,
        personal_email,
        '[email protected]'
    ) AS contact_email
FROM employees;

This query checks for email addresses in order of preference, ensuring every employee has at least a placeholder contact method.

Two-argument alternative: ifnull()

SQLite’s ifnull(X, Y) is equivalent to coalesce(X, Y) when there are exactly two arguments. Choose the spelling that reads more clearly; don’t assume either form is faster without benchmarking the query and data you use.

SELECT coalesce(NULL, 'fallback') AS with_coalesce,
       ifnull(NULL, 'fallback') AS with_ifnull;

Both expressions return fallback. SQLite documents that ifnull() must have exactly two arguments and is equivalent to two-argument coalesce().

Conclusion

SQLite’s coalesce() provides a concise fallback chain with defined left-to-right short-circuit behavior. For comparison with the similarly named functions in other database engines, see SQL NULL handling by database.