Understanding the Postgres ISNULL and ISNOTNULL Conditions

Updated

postgres isnull

To test for NULL, use IS NULL and IS NOT NULL. PostgreSQL also accepts the non-standard postfix operators ISNULL and NOTNULL, which really do work — but there is no ISNOTNULL, and no ISNULL(a, b) function like the one in SQL Server or MySQL. Use COALESCE for that.

SELECT NULL::int ISNULL AS isnull_op, 1 NOTNULL AS notnull_op;
 isnull_op | notnull_op
-----------+------------
 t         | t

SELECT ISNULL(NULL, 'x');
ERROR:  function isnull(unknown, unknown) does not exist

The trap: ISNOTNULL fails silently in a SELECT list

There is no ISNOTNULL in PostgreSQL, and the reason that matters is not that you get an error — it is that sometimes you don’t. In a WHERE clause you get a clean failure:

SELECT * FROM hw_emp WHERE department ISNOTNULL;
ERROR:  syntax error at or near "ISNOTNULL"

In a SELECT list, PostgreSQL parses ISNOTNULL as a column alias, because AS is optional. The query succeeds and hands you the wrong thing:

SELECT 1 AS id, 'sales'::text ISNOTNULL;
 id | isnotnull
----+-----------
  1 | sales

That is the department column renamed, not a boolean. A dashboard built on this shows a column headed isnotnull full of plausible values, and nobody notices.

Three-valued logic: why = NULL never matches

NULL means unknown, so comparing it to anything — including itself — yields NULL, not true. WHERE keeps only rows where the condition is true, so a NULL result is discarded exactly like a false one.

SELECT NULL = NULL AS eq, NULL <> NULL AS neq,
       (NULL = NULL) IS NULL AS eq_is_null,
       NULL IS NOT DISTINCT FROM NULL AS idf;
 eq | neq | eq_is_null | idf
----+-----+------------+-----
    |     | t          | t

IS DISTINCT FROM / IS NOT DISTINCT FROM are the NULL-aware comparison operators: they always return true or false, never NULL. The same asymmetry bites negation. In a 4-row table where two rows have age NULL and one has 31:

SELECT count(*) FROM hw_emp WHERE age <> 31;              -- 1
SELECT count(*) FROM hw_emp WHERE age IS DISTINCT FROM 31; -- 3

NOT IN with a NULL in the list returns nothing

This is the one that reaches production. Four employees in departments sales, ops, sales, hr; a lookup table holding 'sales' and one NULL row:

SELECT name, department FROM hw_emp
WHERE department NOT IN (SELECT dept FROM hw_active);
 name | department
------+------------
(0 rows)

SELECT name, department FROM hw_emp
WHERE department NOT IN (SELECT dept FROM hw_active WHERE dept IS NOT NULL);
 name | department
------+------------
 bo   | ops
 di   | hr

x NOT IN (a, NULL) expands to x <> a AND x <> NULL, and that second term is NULL for every row, so nothing is ever true. IN is unaffected — it only needs one true — which is why the bug survives review. Use NOT EXISTS, which gave the correct two rows here without needing the NULL filter, or filter the subquery explicitly.

Where NULLs are treated as equal

Two places contradict the “NULL is never equal to NULL” rule, and both are per the SQL standard: grouping, and (as of PostgreSQL 15) an opt-in unique index mode.

SELECT d AS department, count(*) FROM (VALUES ('sales'),(NULL),('sales'),(NULL)) v(d)
GROUP BY d ORDER BY d NULLS LAST;
 department | count
------------+-------
 sales      |     2
            |     2          <- all NULLs collapsed into one group

CREATE TEMP TABLE hw_u (email text UNIQUE);
INSERT INTO hw_u VALUES (NULL), (NULL), (NULL);   -- INSERT 0 3, no violation

CREATE TEMP TABLE hw_u2 (email text UNIQUE NULLS NOT DISTINCT);
INSERT INTO hw_u2 VALUES (NULL);
INSERT INTO hw_u2 VALUES (NULL);
ERROR:  duplicate key value violates unique constraint "hw_u2_email_key"
DETAIL:  Key (email)=(null) already exists.

A plain UNIQUE constraint therefore does not stop you loading a million rows with a NULL email. ORDER BY also has an opinion: ascending sorts put NULLs last by default, so NULLS FIRST/NULLS LAST is worth writing explicitly.

COALESCE, NULLIF, and the concatenation gotcha

SELECT 'a' || NULL AS pipe, concat('a', NULL) AS concat_fn,
       coalesce(NULL, NULL, 'fallback') AS coalesce, 10 / nullif(0,0) AS div;
 pipe | concat_fn | coalesce | div
------+-----------+----------+-----
      | a         | fallback |

|| propagates NULL and wipes out the whole string; concat() skips NULL arguments. COALESCE(nickname, first_name) returns the first non-null argument. NULLIF(denominator, 0) turns a zero into NULL so the division returns NULL instead of raising division by zero. Aggregates ignore NULLs entirely — with two of four ages populated, count(*) was 4, count(age) 2, and avg(age) divided by 2, not by 4. Re-running every NULL case on this page needs only a psql connection and about two seconds: isnull-isnotnull-condition.sh creates only temporary tables, so no table, role or database is left behind, and it skips the NULLS NOT DISTINCT check on servers older than PostgreSQL 15.

Aliases beginning with IS are the reason to keep writing AS: it costs three characters and turns a silent mis-column into a syntax error.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.