skip to content

In SQL Server, how do ISNULL and COALESCE differ in result type, evaluation and nullability?

level: middleimportance: must knowfreq 68%

answer

  1. function versus rewritten expression
  2. whose data type wins
  3. a varchar(3) meets 'unknown'
  4. computed column as a key
  5. a subquery can run twice

basics

~20 s

ISNULL takes two arguments and returns the first one's type, truncating a longer replacement; COALESCE takes many and returns the highest-precedence type. COALESCE is rewritten as CASE, so inputs can be evaluated twice, and its result counts as nullable.

solid answer

~40 s

`ISNULL(check, replacement)` is a two-argument T-SQL function; `COALESCE` is standard SQL and takes any number of arguments. Three differences matter. **Type**: `ISNULL` returns the type of its first argument, so with `@code varchar(3)` the call `ISNULL(@code, 'unknown')` returns `'unk'`; `COALESCE` follows `CASE` rules and returns the type with the highest data type precedence, so `COALESCE(name, 0)` is an `int` and fails with Msg 245 on any non-numeric name. **Evaluation**: the optimizer rewrites `COALESCE` as a `CASE` expression, so an argument such as a subquery can be evaluated twice and return different values between evaluations; `ISNULL` evaluates once. **Nullability**: `ISNULL(col, 0)` counts as not nullable and `COALESCE(col, 0)` as nullable, which decides whether a computed column built on it can be a `PRIMARY KEY`.

code

sql · 11 lines
sql
DECLARE @code varchar(3) = NULL;

SELECT ISNULL(@code, 'unknown')   AS isnull_result,    -- 'unk'
       COALESCE(@code, 'unknown') AS coalesce_result;  -- 'unknown'

-- Succeeds: ISNULL makes the computed column non-nullable
CREATE TABLE #demo_isnull
(
    col1 int NULL,
    col2 AS ISNULL(col1, 0) PRIMARY KEY
);

go deeper

for a junior

Recall that ISNULL takes two arguments and is T-SQL only, while COALESCE is standard SQL and accepts a whole list of fallbacks.

for a middle

Explain where the type comes from: ISNULL keeps the first argument's type and can truncate; COALESCE uses type precedence and can force an unwanted conversion.

for a senior

Show you know the production traps: a COALESCE around a subquery evaluated twice under READ COMMITTED, and computed key columns that need ISNULL rather than COALESCE.

for a principal

Weigh portability against T-SQL's behaviour: a style rule preferring COALESCE needs explicit exceptions for typed fallbacks, computed keys and single evaluation.

## Two ways to replace NULL Both expressions return the first non-`NULL` value from their inputs, so in a quick select list they look interchangeable. They are not the same kind of object: - **`ISNULL(check_expression, replacement_value)`** is a T-SQL function with exactly two arguments. - **`COALESCE(expr1, expr2, ...)`** is a standard SQL expression with any number of arguments. SQL Server's optimizer **rewrites it as a `CASE` expression**: `CASE WHEN expr1 IS NOT NULL THEN expr1 WHEN expr2 IS NOT NULL THEN expr2 ... END`. Almost every behavioural difference follows from "function" versus "shorthand for `CASE`". ## Difference 1: the result's data type **`ISNULL`** returns the data type of its **first** argument, unless that argument is a literal `NULL`, in which case the replacement's type is used. The replacement is implicitly converted to that type, and the documentation states plainly that it **can be truncated** if it is longer. With `DECLARE @code varchar(3) = NULL;`, `ISNULL(@code, 'unknown')` returns `'unk'`. **`COALESCE`** follows `CASE` typing: the result has the type with the **highest data type precedence** among all the arguments. `COALESCE(@code, 'unknown')` returns all seven characters. The flip side is a conversion you did not ask for. In SQL Server's precedence list `int` ranks above `varchar`, so: 1. `ISNULL(name, 0)` returns `name` as a string, and `'0'` where it is `NULL`. 2. `COALESCE(name, 0)` is typed `int`, so every **non-null** name must convert to `int`, and the first value such as `'Alice'` raises Msg 245, "Conversion failed when converting the varchar value ... to data type int". When both arguments are untyped `NULL` literals, `ISNULL(NULL, NULL)` returns an `int` `NULL`, while `COALESCE(NULL, NULL)` is rejected with Msg 4127, because at least one argument must be a typed value. ## Difference 2: how often the inputs are evaluated Because `COALESCE` becomes a `CASE` expression, an input can be **evaluated more than once**: once in the `IS NOT NULL` test and again to return it. For a column that only costs a little CPU. For a subquery it matters: the documentation notes that in `COALESCE((subquery), 1)` the subquery is evaluated twice, and under `READ COMMITTED` with concurrent writers the two evaluations can disagree, so the expression can even return `NULL`. The documented remedies are: - use `ISNULL`, which as a function is evaluated **once**; - push the subquery into a derived table and apply `CASE` or `COALESCE` to its single result; - run under `SNAPSHOT` isolation so both evaluations see the same data. The same concern applies to any nondeterministic input, such as a call to `NEWID()`. ## Difference 3: nullability of the result SQL Server records whether an expression can be `NULL`, and the two differ. **`ISNULL(col, 0)`** is treated as **not nullable** when the replacement is not nullable. **`COALESCE(col, 0)`** is treated as **nullable** even though it can never actually return `NULL`. This decides what you can build on top: - a computed column `AS ISNULL(col1, 0)` can be a `PRIMARY KEY`; the same column written with `COALESCE` cannot, and the `CREATE TABLE` fails; - it affects key constraints and whether a scalar user-defined function's result can be treated as deterministic and indexed. ## Summary table | | `ISNULL` | `COALESCE` | |---|---|---| | Arguments | exactly two | two or more | | Standard | T-SQL only | ANSI SQL | | Result type | first argument's type | highest precedence of all arguments | | Long replacement | truncated to first argument | kept | | Evaluation | once | can be repeated (`CASE` rewrite) | | Nullability | not nullable when the replacement is not | nullable | | `(NULL, NULL)` | `int` `NULL` | Msg 4127 | ## Choosing between them - Use **`COALESCE`** when you need more than two fallbacks, want portable SQL, or want the wider type so nothing is truncated. - Use **`ISNULL`** for a computed column that must be a key, for a fallback around a subquery that must be evaluated once, or when you deliberately want the first argument's type. - Neither belongs in a `WHERE` clause to find missing values: write `col IS NULL`. Wrapping a column in either function also hides it from an index seek. In code review, the two questions to ask are "what type does this return?" and "is any argument expensive or nondeterministic?".

  • Why can COALESCE((SELECT ...), 0) return NULL even though 0 is the fallback?
    `COALESCE` is rewritten as `CASE WHEN (subquery) IS NOT NULL THEN (subquery) ELSE 0 END`, so the subquery runs twice. Under `READ COMMITTED`, a concurrent write between the two runs can make the first see a value and the second see none, and the expression returns that `NULL`. Use `ISNULL`, which evaluates once, or move the subquery into a derived table.
  • Is ISNULL in SQL Server the same as IS NULL or a function that tests for NULL?
    No. `ISNULL(a, b)` returns a replacement value; it does not return true or false. To filter missing values you write the predicate `col IS NULL`. Writing `WHERE ISNULL(col, '') = ''` works logically but wraps the column in a function, which prevents an index seek on it and treats empty strings and `NULL` alike.

ISNULL pours the replacement into the first argument's container: if that container is a three-character box, 'unknown' arrives as 'unk'. COALESCE picks the roomiest container among all its arguments, even when that container is of a type the other values cannot fit into.

  • ISNULL and COALESCE always return the same type.
  • COALESCE evaluates each argument exactly once, like a function.
  • ISNULL returns the replacement in its own data type.
  • A computed column using COALESCE can serve as a primary key.
  • COALESCE(name, 0) safely returns the name or zero.