// conditional reference

SQL COALESCE function

Returns the first argument that is not NULL: a display value for missing data, a default, or a fallback chain such as COALESCE(mobile, work_phone, home_phone).

カテゴリ
条件付き
Returns
the common type of all arguments
In this category
1 of 43

構文

COALESCE(value1, value2, ...)

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle はい Supported under this name.

例

Any engine

SELECT COALESCE(nickname, first_name, 'Anonymous') AS display_name
FROM users;

Any engine

SELECT COALESCE(SUM(amount), 0) AS total FROM payments;

知っておくと便利なこと

  • All arguments must share a type. On SQL Server, the highest-precedence type wins: COALESCE(int_col, '') silently returns 0, and COALESCE(int_col, 'none') fails at run time converting 'none' to int. PostgreSQL rejects COALESCE(int_col, '') outright. Cast to a common type.
  • Evaluation stops at the first non-NULL argument, but SQL Server rewrites COALESCE as a CASE expression, so a subquery argument can run twice. For an expensive lookup, compute it once in a CTE, or use ISNULL for two arguments.
  • An all-NULL COALESCE returns NULL: COALESCE(a, b, 0) with a final literal guarantees a non-NULL result.

Questions about COALESCE

What does COALESCE return if everything is NULL?

NULL. Add a literal as the last argument when the caller cannot handle NULL: COALESCE(a, b, 0).

COALESCE or ISNULL / IFNULL / NVL?

COALESCE is the SQL standard and takes any number of arguments; the others are engine dialects that take exactly two. Prefer COALESCE for portability.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.