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.
Related on SQLly
- Replacing NULL in output: COALESCE, ISNULL, NVL, IFNULL Dialect comparison
- Sorting with COALESCE in ORDER BY Dialect comparison
- Find duplicate index candidates Snippet
- Fill gaps with a calendar spine Snippet
- Full outer compare of two result sets Snippet
- Find tables without a primary key Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.