// dialect comparison

Replacing NULL in output: COALESCE, ISNULL, NVL, IFNULL

COALESCE everywhere; ISNULL, IFNULL and NVL are the same idea with local names.

Filed under Querying

The verdict

Write COALESCE and the query runs everywhere; the shorthands only matter when reading existing code. One real behavioral difference to know: in SQL Server, ISNULL's result type comes from the first argument, so ISNULL(varchar_col, longer_default) silently truncates where COALESCE does not.

Where they differ

COALESCE(a, b, c) returns the first non-NULL argument and works in all five engines. Each engine also ships a two-argument version under a different name, which is the usual porting friction.

How each engine writes it

SQL Server

SELECT COALESCE(nickname, name) AS display_name FROM users;

ISNULL(nickname, name) is the T-SQL shorthand; its return type follows the first argument, COALESCE uses type precedence.

PostgreSQL

SELECT COALESCE(nickname, name) AS display_name FROM users;

COALESCE is the only built-in option, and the standard one.

MySQL

SELECT IFNULL(nickname, name) AS display_name FROM users;

IFNULL is the two-argument shorthand; COALESCE takes many arguments.

SQLite

SELECT IFNULL(nickname, name) AS display_name FROM users;

IFNULL and COALESCE are both built in; no NVL.

Oracle

SELECT NVL(nickname, name) AS display_name FROM users;

NVL is the two-argument shorthand; NVL2(a, b, c) returns b when a is not NULL and c when it is.

Questions that come up

COALESCE or ISNULL: which should I use?

COALESCE. It is standard, takes any number of arguments, and its result type follows the normal precedence rules. ISNULL, IFNULL and NVL are fine to read in existing code, but portable code uses COALESCE.

Why is COALESCE slow with a subquery in SQL Server?

SQL Server expands COALESCE((SELECT …), 0) into CASE WHEN (SELECT …) IS NOT NULL THEN (SELECT …) ELSE 0 END, so the subquery can run twice. ISNULL((SELECT …), 0) evaluates it once. Oracle's NVL, by contrast, evaluates both arguments every time, while its COALESCE stops at the first non-NULL one.

How do I replace NULL in an aggregate?

Wrap the aggregate: COALESCE(SUM(x), 0). SUM over zero rows, or over only NULLs, returns NULL rather than 0. Writing SUM(COALESCE(x, 0)) does not fix that case, because SUM already skips NULL rows.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.