How to check for null/empty/whitespace values with a single test?
I'd like to write a SELECT statement that uses just one test to return columns with no value (null, empty, or all spaces).
I thought this would work:
SELECT column_name from table_name WHERE column_name NOT LIKE '%_%';
But this does not work for NULL values.
Of course I can add
OR column_name IS NULL
and it will work, but I'd like a way that uses a single test.
Solution 1:
Functionally, you should be able to use
SELECT column_name
FROM table_name
WHERE TRIM(column_name) IS NULL
The problem there is that an index on COLUMN_NAME would not be used. You would need to have a function-based index on TRIM(column_name) if that is a selective condition.
Solution 2:
SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''
ISNULL(column_name, '')
will return '' if column_name is NULL, otherwise it will return column_name.
UPDATE
In Oracle, you can use NVL
to achieve the same results.
SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''
Solution 3:
The NULLIF function will convert any column value with only whitespace into a NULL value. Works for T-SQL and SQL Server 2008 & up.
SELECT [column_name]
FROM [table_name]
WHERE NULLIF([column_name], '') IS NULL
Solution 4:
While checking null or Empty
value for a column, I noticed that there are some support concerns in various Databases.
Every Database doesn't support TRIM
method.
Below is the matrix just to understand the supported methods by different databases.
The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:
-
MySQL:
TRIM(), RTRIM(), LTRIM()
-
Oracle:
RTRIM(), LTRIM()
-
SQL Server:
TRIM(), RTRIM(), LTRIM()
How to Check Empty/Null/Whitespace :-
Below are two different ways according to different Databases-
The syntax for these trim functions are:
-
Use of Trim to check-
SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL
-
Use of LTRIM & RTRIM to check-
SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL
Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName
from UserDetails
table if it has an empty LastName
Hoping this will help others too :)
Solution 5:
This phpMyAdmin query is returning those rows, that are NOT null or empty or just whitespaces:
SELECT * FROM `table_name` WHERE NOT ((`column_name` IS NULL) OR (TRIM(`column_name`) LIKE ''))
if you want to select rows that are null/empty/just whitespaces just remove NOT.