SQL check for empty or blank strings
Three different questions hide in is this empty: NULL, '', and whitespace-only. Each engine answers them with slightly different tools.
- Categoría
- Strings
- Returns
string- In this category
- 67 of 172
Sintaxis
col IS NULL OR col = ''
NULLIF(TRIM(col), '') IS NULL
Each block is a separate form. The support table and the examples show which engine takes which.
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | Supported under this name. |
| SQLite | Sí | Supported under this name. |
| Oracle | Sí | Supported under this name. |
Ejemplos
SQL Server
SELECT * FROM t WHERE col IS NULL OR col = '';
PostgreSQL
SELECT * FROM t WHERE NULLIF(TRIM(col), '') IS NULL;
Oracle
SELECT * FROM t WHERE col IS NULL; -- covers '' and NULL
Conviene saberlo
- NULL and '' are different on all engines except Oracle: col = '' never matches NULL, so a complete empty test needs both conditions, or NULLIF(TRIM(col), '') IS NULL for blanks too.
- Whitespace-only values need TRIM first; tabs and newlines need a character-set trim or a regex test such as col ~ '^\s*$' (PostgreSQL) or REGEXP_LIKE(col, '^[[:space:]]*$') (MySQL, Oracle; MySQL would read '\s' in a literal as a plain s).
- SQL Server's LEN ignores trailing spaces, so LEN(' ') is 0, but LEN(' x') counts leading spaces, so length tests are asymmetric.
- Oracle collapses the whole question: '' is NULL, so col IS NULL finds empty and blank-and-trimmed values alike.
Questions about Checking for empty strings
Why does col = '' miss rows?
Those rows hold NULL, and NULL = anything is unknown. Use (col IS NULL OR col = ''), or the blank-inclusive NULLIF(TRIM(col), '') IS NULL.
How do I catch whitespace-only values?
Trim first: NULLIF(TRIM(col), '') IS NULL catches '', ' ' and NULL in one test, with a character-set or regex trim if tabs and newlines count as blank.
What is different on Oracle?
The empty string is NULL, so col IS NULL alone covers '' too, and TRIM('') also yields NULL. Tests ported from other engines over-count on Oracle.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
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.