Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL not equals & null

We'd like to write this query:

select * from table 
where col1 != 'blah' and col2 = 'something'

We want the query to include rows where col1 is null (and col2 = 'something'). Currently the query won't do this for the rows where col1 is null. Is the below query the best and fastest way?

select * from table 
where (col1 != 'blah' or col1 is null) and col2 = 'something'

Alternatively, we could if needed update all the col1 null values to empty strings. Would this be a better approach? Then our first query would work.


Update: Re: using NVL: I've read on another post that this is not considered a great option from a performance perspective.

like image 296
Marcus Leon Avatar asked Mar 12 '09 00:03

Marcus Leon


1 Answers

In Oracle, there is no difference between an empty string and NULL.

That is blatant disregard for the SQL standard, but there you go ...

In addition to that, you cannot compare against NULL (or not NULL) with the "normal" operators: "col1 = null" will not work, "col1 = '' " will not work, "col1 != null" will not work, you have to use "is null".

So, no, you cannot make this work any other way then "col 1 is null" or some variation on that (such as using nvl).

like image 145
Thilo Avatar answered Nov 04 '22 09:11

Thilo