← Back to SQL, page 21

sql-0413 · Easy fresher

What do COALESCE(NULL, '', 'x'), IFNULL(NULL, 0) and NULLIF(5, 5) return?

COALESCE returns '' because the empty string is the first non-NULL argument, IFNULL returns 0, and NULLIF(5, 5) returns NULL because its two arguments are equal.

Full answer
sql
SELECT COALESCE(NULL, '', 'x') AS a, IFNULL(NULL, 0) AS b, NULLIF(5, 5) AS c, NULLIF(5, 6) AS d;
abcd
''0NULL5

COALESCE stops at the first argument that is not NULL, and an empty string qualifies even though it looks blank, so 'x' is never reached. IFNULL is SQLite's two-argument form of COALESCE. NULLIF(a, b) returns NULL when a equals b and a otherwise, which is why NULLIF(5, 6) is 5. Combining them, COALESCE(NULLIF(trim(name), ''), 'unknown') treats blank and NULL alike. PostgreSQL has COALESCE and NULLIF but not IFNULL (PostgreSQL behaviour stated, not run here).

sql
SELECT COALESCE(NULL, '', 'x') AS a, IFNULL(NULL, 0) AS b, NULLIF(5, 5) AS c, NULLIF(5, 6) AS d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • COALESCE returns the first non-NULL
  • Empty strings are not NULL
  • NULLIF turns equal values into NULL
  • IFNULL is SQLite and MySQL only

Common mistakes

  • Expecting COALESCE to skip empty strings

Follow-ups

  • How would you treat blank and NULL the same?
  • Where is NULLIF useful besides division?

Tips

  • Check each argument in order