MySQL COALESCE() Function
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-NULLresult 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 returnNULLjust because one argument isNULL—its entire purpose is skippingNULLvalues. It returnsNULLonly when every argument evaluates toNULL. - Empty strings are not NULL:
COALESCE('', 'fallback')returns''(an empty string), not'fallback'. Wrap nullable blank strings withNULLIF(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 beNULLwhen both columns areNULL. - 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.