// dialect comparison

NULL versus empty string in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

In Oracle, '' IS NULL is true. Everywhere else it is false. That one fact rewrites your WHERE clauses.

Filed under Types & casting

The verdict

The same SQL is right on four engines and redundant on the fifth. A bare IS NULL check is complete on Oracle but misses '' rows everywhere else; NULLIF(note, '') IS NULL catches both cases on all five.

Where they differ

For the four engines the empty string and NULL are different values, and both checks are needed when text columns can hold either. Oracle makes the distinction impossible to express because zero-length text simply is NULL.

How each engine writes it

SQL Server

SELECT * FROM t WHERE note = '' OR note IS NULL;

'' and NULL are distinct values, so a column that allows both needs both checks, unless a NOT NULL or CHECK (note <> '') constraint rules one out.

PostgreSQL

SELECT * FROM t WHERE note = '' OR note IS NULL;

Distinct values, as ANSI intends. IS NOT DISTINCT FROM compares them without the three-valued-logic trap.

MySQL

SELECT * FROM t WHERE note = '' OR note IS NULL;

Distinct values. Note that NULL fails both = '' and <> '' comparisons.

SQLite

SELECT * FROM t WHERE note = '' OR note IS NULL;

Distinct values. In ascending order NULL sorts first, then '', then 'a'.

Oracle

SELECT * FROM t WHERE note IS NULL;

'' IS NULL evaluates to true: Oracle treats zero-length character values as NULL, so you cannot store an empty string in a column at all.

Questions that come up

Why does Oracle treat '' as NULL?

A long-standing implementation choice, documented and never changed because real code depends on it. VARCHAR2 columns cannot distinguish empty from missing.

How do I normalize mixed data before migrating to Oracle?

Collapse '' to NULL first (UPDATE t SET note = NULL WHERE note = '';), or comparisons that matched empty strings will silently start matching NULL semantics.

Does this affect VARCHAR in other engines?

No. SQL Server, PostgreSQL, MySQL and SQLite all store '' as a real value. Only Oracle collapses it, in VARCHAR2 and CHAR columns alike.

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.