Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compatible SQL to test for not null and not empty strings

Tags:

I want to have compatible SQL for both Oracle database and Microsoft SQL server.

I want a compatible SQL expression that will return true for not null and not empty strings.

If I use:

column <> '' 

it will work on Microsoft SQL server but not on Oracle database (as '' is null for Oracle)

If I use:

len(column) > 0 

it will work on Microsoft SQL server but not on Oracle database (since it uses length() )

like image 623
Eduardo Avatar asked Jun 23 '11 16:06

Eduardo


People also ask

How do you check for is not null and is not empty string in SQL Server?

Description. The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Is NULL and empty string the same in SQL?

NULL is used in SQL to indicate that a value doesn't exist in the database. It's not to be confused with an empty string or a zero value. While NULL indicates the absence of a value, the empty string and zero both represent actual values.


2 Answers

NULLIF is available on both Oracle (doc) and SQL Server (doc). This expression should work:

NULLIF(column, '') IS NOT NULL 

In both servers, if column is NULL, then the output of NULLIF will just pass the NULL value through. On SQL Server, '' = '', so the output of NULLIF will be NULL. On Oracle, '' is already NULL, so it gets passed through.

This is my test on SQL Server 2008 R2 Express:

WITH SampleData AS     (SELECT 1 AS col1, NULL AS col2      UNION ALL      SELECT 2, ''      UNION ALL      SELECT 3, 'hello') SELECT *   FROM SampleData  WHERE NULLIF(col2, '') IS NOT NULL; 

And this is my test case on Oracle 10g XE:

WITH SampleData AS     (SELECT 1 AS col1, NULL AS col2 FROM DUAL      UNION ALL      SELECT 2, '' FROM DUAL      UNION ALL      SELECT 3, 'hello' FROM DUAL) SELECT *   FROM SampleData  WHERE NULLIF(col2, '') IS NOT NULL; 

Both return 3 as expected.

like image 184
Cheran Shunmugavel Avatar answered Oct 29 '22 00:10

Cheran Shunmugavel


How about

CASE WHEN column = '' THEN NULL ELSE column END IS NOT NULL 
like image 33
Gary Myers Avatar answered Oct 29 '22 02:10

Gary Myers