Lesson

MySQL COALESCE() Function

10 min reading
Free Course

MySQL COALESCE() Function

The MySQL COALESCE() function scans a list of arguments from left to right and returns the first value that is not NULL. If every argument evaluates to NULL, COALESCE() returns NULL.

Syntax

COALESCE(value1, value2, ..., valueN)
  • value1, value2, ...: Two or more expressions (or one in MySQL) evaluated in order until a non-NULL result appears.

Unlike IFNULL(), which only accepts two arguments, COALESCE() is standard ANSI SQL and accepts any number of fallback expressions. It also uses short-circuit evaluation, stopping as soon as it finds a non-NULL value.

Practical Example

In demo_customers, a customer might have a mobile phone, an office phone, or neither. COALESCE() picks the best available contact number in priority order.

SELECT
    customer_id,
    full_name,
    COALESCE(mobile_phone, office_phone, 'No Phone Listed') AS primary_contact
FROM demo_customers
ORDER BY customer_id;
customer_id full_name primary_contact
1 Elena Rostova +1-555-0101
2 David Kim +1-555-0144
3 Nora Patel No Phone Listed

Common Mistakes & NULL Behavior

  • NULL behavior: COALESCE() does not return NULL just because one argument is NULL—its entire purpose is skipping NULL values. It returns NULL only when every argument evaluates to NULL.
  • Empty strings are not NULL: COALESCE('', 'fallback') returns '' (an empty string), not 'fallback'. Wrap nullable blank strings with NULLIF(mobile_phone, '') first: COALESCE(NULLIF(mobile_phone, ''), office_phone, 'N/A').
  • All-NULL edge case: If you call COALESCE(col1, col2) without a literal fallback at the end, the result can still be NULL when both columns are NULL.
  • Implicit type coercion: Passing an integer and a string (COALESCE(discount_pct, 'None')) causes MySQL to return a string type for the whole column. Keep fallback types consistent for numeric math.

Frequently Asked Questions

Should I use COALESCE() or IFNULL() in MySQL?

Prefer COALESCE() for most queries because it accepts three or more arguments and follows standard ANSI SQL across MySQL, PostgreSQL, and SQLite.

Does COALESCE() evaluate every argument?

No. MySQL evaluates arguments lazily from left to right and stops as soon as it finds the first non-NULL value.

How do I make COALESCE() treat empty strings as missing?

Combine COALESCE() with NULLIF(col, ''), which turns empty strings into NULL before COALESCE() checks the next fallback.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum