5

I have to write an SQL SELECT statement which is valid for MS SQL Server and Oracle. I have to work with old customer databases, so I cannot change anything in the db design...

Problem is that the table has a nullable column 'project' which is a varchar that is in some cases filled with an empty string - which is translated by oracle to NULL. So how do I select all columns that have an NON empty 'project'?

WHERE project IS NOT NULL                   works for oracle
WHERE project <> ''                         works for MS
WHERE project IS NOT NULL AND project <> '' works for MS, but not for Oracle

Thanks, Marko

1
  • It's like writing a code statement that is valid in both Java and C++ :) Commented Nov 19, 2013 at 11:47

3 Answers 3

7

Because the condition '' = '' will be true only in SQL-Server (it's equivalent to '' IS NOT NULL) and the condition '' IS NULL will be true only in Oracle, you can use this:

WHERE ( project > '' AND '' = '')              -- for SQL-Server
   OR ( project IS NOT NULL AND '' IS NULL)    -- for Oracle

Note that if you have values that are only spaces, they will be treated differently between SQL-Server and Oracle. Test SQL-Fiddle-1 (Oracle) and SQL-Fiddle-2 (SQL-Server).

Sign up to request clarification or add additional context in comments.

Comments

2

You can use NULLIF(), which is available in both SQL Server and Oracle (it's part of the ANSI standard).

select *
  from table
 where nullif(project, '') is not null

It works because Oracle evaluates the empty string to NULL. It's worth noting that Oracle does not evaluate NULLIF() if the first expression is NULL, but it does work this way round.

Comments

-2

facts:

  • Oracle translate empty to NULL
  • SQL Server does not translate.

So if you have a Oracle and SQL Server database with same content, the result is the same, something you really want

where (project is not null OR project <> '')

3 Comments

This will include the empty strings in SQL-Server.
In oracle the empty string is translate to NULL so with the results form oracle and sql are the same with this statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.